Symfony2 login event listener

Recommended reading: Symfony2 Doctrine Migrations with Unique Indexes (Slugs)

If you want to do some custom stuff when a user logs in, in Symfony2 you have to add an event listener that will fire after the user successfully logged in. The event that is fired is security.interactive_login and to hook to it you have to specify this in services.yml file form your bundle Resources/config directory:

    class: Dbla\UserBundle\Listener\LoginListener
    arguments: [@doctrine]
      - { name: kernel.event_listener, event: security.interactive_login, method: onLogin }

After that create a directory Listener in your bundle and in it the LoginListener.php file with the LoginListener class:

namespace Dbla\UserBundle\Listener;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Bundle\DoctrineBundle\Registry as Doctrine;

class LoginListener
  protected $doctrine;

  public function __construct(Doctrine $doctrine)
    $this->doctrine = $doctrine;

  public function onLogin(InteractiveLoginEvent $event)
    $user = $event->getAuthenticationToken()->getUser();

      $user->setLastLogin(new \DateTime());
      $user->setNumberOfLogins($user->getNumberOfLogins() + 1);
      $em = $this->doctrine->getEntityManager();

Clear the cache and that’s all! Let me know in the comments if you encounter any problems.

One thought on “Symfony2 login event listener”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may 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>