Event Listener (after login) on Symfony 2

If you need to do some kind of action after the user has logged-in on your system, you should add an event listener.

First, you need to create a service.

On your app/config.yml you must define your service:

my.service:
        class: YourApp\YourBundle\Listener\LoginListener
        arguments: [@doctrine]
        tags:
          - { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin }

After that you need to code your listener

<?php
 
namespace YourApp\YourBundle\Listener;
 
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
 
class LoginListener
{
    /**
     * @var Doctrine\Bundle\DoctrineBundle\Registry
     */
    private $doctrine;
 
    public function __construct(Doctrine $doctrine)
    {
        $this->doctrine = $doctrine;
    }
 
    public function onInteractiveLogin(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();
 
        if ($user) {
            // your action with the current user
 
            $this->doctrine->getEntityManager()->persist($user);
            $this->doctrine->getEntityManager()->flush();
        }
    }
}

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>