Reputation: 4199
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?
Note: I am using Slim PHP v3
Upvotes: 1
Views: 1146
Reputation: 80
2 solutions come into mind:
You could also try to have the common functionality in a separate Trait.
I won't do the new SecondController($container) inside the constructor of the FirstController unless you need it at every controller-hit. I like lazy loading, so it will load only when needed.
Upvotes: 1
Reputation: 4199
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
}
}
Upvotes: 0
Reputation: 15629
If your OrderController
wants to call a method foo
from AccessController
, you should think about moving foo
somewhere else. That's an good indicator for wrong SRP
There are two possibilities
foo
belongs to/is relevant for every Controller and has something to do with controlling: Just move it to the parent class.
foo
is relevant to only a few classes: Move it to the class, it belongs to. This could be an helper class, some domain model class, or something else. Maybe you have to intruduce a new class to do this.
Upvotes: 0
Reputation: 43441
If your AddressController
and OrderController
has same parent class, than move these methods to parent:
class AddressContoller extends Controller {
public function test() {
$this->methodFromParent();
}
}
If not, create new object of that class and call method. Method must be public
class AddressContoller extends Controller {
public function test() {
$order = new OrderController();
$order->publicMethodInOrderClass();
}
}
Upvotes: 0