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:
- It is to protect us regarding a potential serious design error? If this is the case, could you give me an example of what serious can happen if two dependent services could "live together"?
- It is purely technical? I.e. because it is not possible to call both constructors. If this is the root reason, why not solve it by forcing service constructors to be empty and have an init method?
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