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

Posted October 17th, 2014 in Symfony2 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.

Login event listener in Symfony2

Posted July 11th, 2011 in Tehnikalije by Metod

So you have a Symfony2 project under construction. Login works. Now you want to execute some code right after the user successfully logs in.

The solution: Make a custom event listener.

An event listener is actually a service with a proper tag associated with it. So first step is to register the listener. The configuration file shown corresponds to the listener in file Acme/UserBundle/Listener/LoginListener.php. You can read more about services here.

In services.yml:

Let’s go through the configuration.

class defines the listener class.

With arguments we inject services that this listener depends on. In this case the security.context service for retrieving the User object and doctrine service for EntityManager.

tags is important. Every listener must be tagged with kernel.event_listener and must specify it’s event. For successful login that event is security.interactive_login. You can also specify the optional method tag.

Ok, our listener is registered. Let’s create it.

The above code should be pretty self-explanatory. The only required method is onSecurityInteractiveLogin(InteractiveLoginEvent $event). You do not need the other stuff, but you probably will if you want to modify the User object, or something else in the DB.