Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Circular References in Symfony2's Dependency Injection?

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:

  1. 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"?
  2. 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

like image 659
Vincent Pazeller Avatar asked Oct 19 '22 20:10

Vincent Pazeller


1 Answers

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.

enter image description here

like image 156
Adam Elsodaney Avatar answered Dec 28 '22 06:12

Adam Elsodaney