I am a big fan of dependency injection, but something bothers me and I was wondering whether someone could give me an explanation:
It is not possible to create two services that depends on each other, because we will get a "Circular Reference" exception. I think everyone using symfony2 has met this error.
While I understand very well this error, I meet it sometimes because with a lot of services, comes complexity... and, maybe also because designing/sizing services is not easy.
Therefore, I was wondering about the root cause of this error:
I.e.:
class MyService1{
private $service2;
public function __construct(){ //empty constructor
...
}
protected function init(MyService2 $service2, ...){
$this->service2 = $service2;
}
}
class MyService2{
private $service1;
public function __construct(){ //empty constructor
...
}
protected function init(MyService1 $service1, ...){
$this->service1 = $service1;
}
}
And then instantiate both services:
$service1 = new MyService1();
$service2 = new MyService2();
$service1->init($service2);
$service2->init($service1);
I'm pretty sure there is something I don't have understood in depth. So could someone explain me why we are prevented to create circular references in the container?
Thank you
Ideally your services would adhere to the dependency inversion principle.
That is, high-level components would depend on low-level components but not the other way round. Additionally for higher cohesion, this dependency would be via an abstraction or interface.
See this question from the Programmers SE site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With