Event Driven Architecture is a very powerful pattern for modern PHP Enterprise Systems Applications. In Symfony is very easy to implement actions that are executed when a particular type of event happens using listeners.
Let's say you want to log every time a user logs in to your application. You can achieve this by creating a listener that listens to the security.interactive_login event, which is dispatched when a user logs in using the Symfony Security component.
- First, create a new listener class (e.g. UserLoginListener) and implement the EventSubscriberInterface interface. This interface requires you to define a static method getSubscribedEvents() that returns an array of events that the listener should subscribe to:
<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class UserLoginListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
InteractiveLoginEvent::class => 'onUserLogin',
];
}
public function onUserLogin(InteractiveLoginEvent $event)
{
// TODO: Implement the code to log the user login event
}
}
- In the onUserLogin() method, implement the code to log the user login event. You can use any logging library or service of your choice (e.g. Monolog or Psr\Log), or simply write the log to a file or database. For example, you can use the LoggerInterface service provided by Symfony to log the event to a file:
use Psr\Log\LoggerInterface;
public function onUserLogin(InteractiveLoginEvent $event, LoggerInterface $logger)
{
$user = $event->getAuthenticationToken()->getUser();
$logger->info('User ' . $user->getUsername() . ' has logged in');
}
- Finally, register the listener as a service in your Symfony application's configuration file (e.g. config/services.yaml):
services:
App\EventListener\UserLoginListener:
tags:
- { name: kernel.event_subscriber }
The kernel.event_subscriber tag tells Symfony to automatically register the listener as an event subscriber, based on the events returned by the getSubscribedEvents() method.
With this implementation, every time a user logs in to your application, the onUserLogin() method of the UserLoginListener class will be called, and the user login event will be logged to the specified log file.
Further reading:
What is a listener in Symfony Framework