Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading dependencies with symfony DI

Currently I've got a Symfony2 DI container instance ready with a service and all it's dependencies. Lets say for example I have a Car class and it has Engine and Lights as dependencies.

In my current setup both these dependencies are automatically created through setter injection when the Car object is created, but it might very well be that my Car object won't need it's lights this time around thus it doesn't explicitly need to create an instance of this dependency.

Is there a way to achieve this in Symfony DI? Thus only creating an instance of the Lights object when needed? My guess is it'll be some sort of Proxy implementation like Doctrine has but as far as i've seen it doesn't exist in Symfony DI.

like image 517
ChrisR Avatar asked Jul 10 '12 22:07

ChrisR


2 Answers

Inject the dedendencies that are mandatory through the Constructor via your services.yml, automatically.
If you have optional dependencies inject them through a setter in your Controller when you need them.

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

Of course your Cars class must be designed like so and you have to direct the injections yourself in your controller, or whereever needed, code.

like image 142
ivoba Avatar answered Sep 28 '22 07:09

ivoba


Question is already answered, but for who needs this functionality, lazy services are implemented in Symfony 2.3.

You need to install the ProxyManager bridge.

You can find official documentation here.

like image 26
Elorfin Avatar answered Sep 28 '22 07:09

Elorfin