Rihards Steinbergs

Web developer, gamer and fan of everything scifi.

Symfony 4: Login Event Listener

Background information

This might be documented somewhere already, and probably also blogged about already. But at the time when I was implementing this myself my Google-fu was failing me.

So I thought I’d document this seemingly very common feature, in case someone else is stuck and is searching for an answer.

Keep in mind this is for Symfony 4. At least that’s the version I wrote and tested this for.

Event Listeners

While your application is being executed Symfony triggers a lot of event notifications, and your application can listen to these events and respond to them as well.

First you need to create an event listener that listens to security.interactive_login event. You do so by adding the following piece to config/services.yaml:

App\EventListener\LoginListener:
    tags:
        - { name: 'kernel.event_listener', event: 'security.interactive_login' }

Now that we have the event listener configured, let’s write the code to be executed:

// src/EventListener/LoginListener.php

namespace App\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use App\Entity\User;

class LoginListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        // Get the User entity.
        $user = $event->getAuthenticationToken()->getUser();

        // Update your field here.
        $user->setLastLogin(new \DateTime());

        // Persist the data to database.
        $this->em->persist($user);
        $this->em->flush();
    }
}

In Summary

It’s that simple, and I’m amazed by the amount of thought and work has gone into Symfony to make things easier and quicker to develop.

Some might argue that having too much “magic” in a framework might not be good.

But from my experience so far with Symfony 4 I’m constantly amazed at how much more efficient I’m with this framework and how little “boilerplate” code I have to write to get things going.

Instead, I can concentrate on creating my application.