Detect if a synthetic service has been set in Symfony2 Dependency Injection container

Posted October 17th, 2014 in Symfony2 and tagged , , , by Metod

If you are using the Symfony2 DependencyInjection component, you might have run into synthetic services.

If I quote from the docs:

Synthetic services are services that are injected into the container instead of being created by the container.

So, what do we do if we want to detect if a service has already been injected or not? Turns out that the definition of the synthetic service gets removed when it is injected into the container. So we can just check if the definition for the service exists. Below is a quick gist to get the general idea.