Search code examples
phpoopslimslim-3

Access functions of other classes in SlimPHP


I have to different classes in my Slim PHP framework, named OrderController & AddressController. I want to access some function of AddressController inside OrderController to reduce code redundancy.

But can't get a way to do it, I got how to do it in pure PHP setup, but how to do it in Slim PHP framework?

The PHP way to do this is as follows:

class A {
    private $xxx;

    public function __construct() {
        $this->xxx = 'Hello';
    }

    public function getXXX() {
        return $this->xxx;
    }
}

class B {
    private $a;

    public function __construct(A $a) {
        $this->a = $a;
    }

    function getXXXOfA() {
        return $this->a->getXXX();
    }
}

$a = new A();
$b = new B($a);

$b->getXXXOfA();

How to achieve this dependancy injection in Slim?

Slim PHP Framework

Note: I am using Slim PHP v3


Solution

  • After a lot of reseach I finally manage to get a solution! Posting it here so if anyone in future might get help from it:

    class FirstController 
    {
        protected $container;
        protected $db;
        protected $view;
        protected $second;
    
        // constructor receives container instance
        public function __construct(\Interop\Container\ContainerInterface $container) {
            $this->second = new SecondController($container);
            $this->container = $container;
            $this->db = $this->container->db;
            $this->view = $this->container->view;
        }
    
        public function LocalFunction(){
            $this->second->otherFunction();
            //call the functions in other classes as above
        }
    
    }