Reputation: 14467
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.
Upvotes: 7
Views: 3327
Reputation: 2497
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.
Upvotes: 2
Reputation: 6026
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.
Upvotes: 2
Reputation: 34105
It's not a pretty workaround, but you can try injecting the whole DIC, then getting the Light and Engine services when neccessary.
I was thinking about something like this 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;
}
Upvotes: 0
Reputation: 25315
A very interesting question, but I don't think it's possible within Symfony2's Dependency Injection Container. The container is only aware of what you tell it - in this case, you have a dependency that's conditional on a specific use-case. Plus, the registration of services happens early on in the app's life, so I don't see how you could get this to work.
Maybe you should use the Factory pattern. Register a CarFactory
as a service, and then when fetching a Car
instance, you can specify that it should include a Light
dependency.
Can I ask why you want to achieve this? There may be a simpler solution.
Upvotes: 1