Lazy boot dependencies with symfony DI

I currently have a Symfony2 DI container instance ready with the service and all its dependencies. Say, for example, I have a Car class, and it has Engine and Lights as dependencies.

In my current setup, both of these dependencies are automatically created using the setter installation when the Car object is created, but it may well be that my Car object will not need it, it is lit this time, so it clearly does not need to instantiate this dependency.

Is there a way to achieve this in Symfony DI? Thus, only if necessary by creating an instance of the Lights object? I assume that this will be some kind of proxy implementation, for example Doctrine, but as far as I saw that it is not in Symfony DI.

+7
source share
4 answers

Embed the conventions that are required using the constructor through your services.yml automatically.
If you have additional dependencies, you can enter them through the installer in your controller when you need them.

$this->container->get('cars')->setLights(new \Namespace\Lights()); 

Of course, your Cars class should be designed this way, and you need to direct the injections yourself to your controller or, if necessary, code.

+2
source

The question has already been given, but for those who need this feature, Symfony 2.3 implements lazy services.

You need to install ProxyManager bridge .

You can find the official documentation here .

+2
source

Very interesting question, but I do not think this is possible in the Symfony2 Dependency Injection Container. The container only knows what you tell him - in this case, you have a dependency that depends on the specific use case. In addition, the registration of services occurs at an early stage in the life of the application, so I do not see how you can make it work.

Perhaps you should use the Factory pattern. Register CarFactory as a service, and then by retrieving the Car instance, you can indicate that it should include the Light dependency.

May I ask why you want to achieve this? There may be a simpler solution.

+1
source

This is not a very workaround, but you can try to introduce the entire DIC, and then get the necessary Light and Engine services.

I was thinking of something similar to a method in the Car class:

 protected function getLightService() { if (!$this->light) { //so we reuse the first instance $this->light = $this->dic->get("car.light"); } return $this->light; } 
0
source

All Articles