Search code examples
symfonyservicedependency-injectiondependenciesextending

Is it possible to extend services dynamically in a dependency injection?


I am working on a Symfony2 project. Symfony has a very cool dependency injection system, but I am wondering if it's possible to dynamically extend some services...

For instance, I have a vendor service X, registered by a third party library/bundle. Now, I need to extend that service, let's call that one Y... I can do that by using the same service ID in the services configuration. So that's all good...

But now, I need a service Z that extends from Y, without the service knowing it's actually extending from Y instead of X (since the vendor service is X), so I can use service Z as if it were X in all descending application logic without losing the functionality of Y.

I hope my explaination makes a little bit of sense, basically my question is: is this possible? And if so, how should I go about achieving this?


Solution

  • You can decorate an existing service instead of replacing it: http://symfony.com/doc/current/components/dependency_injection/advanced.html#decorating-services (in case more than one definition is decorating an existing one, you can also control the order in which the decoration is applied).