How to Work With Events in Symfony 2 Framework
Azoft Blog How to Work With Events in Symfony 2 Framework

How to Work With Events in Symfony 2 Framework

By Alexey Romanenko on May 23, 2013

We have already looked at some notable data visualisation features of Symfony 2 in an earlier post. Today's post will be about events — a handy concept, often used for adding your own functionality to the Symfony 2 framework.

Symfony 2 provides classes to build your own events, but you can also subscribe to many existing events. The built-in profile includes an Events tab that lists all the events, handled in the most recent request.

Symfony 2 profile

In this post I'd like to show you how to work with events and, most importantly, how to subscribe to them in order to solve the following problems:

  • Updating the last login date for a user;
  • Redirecting a user to the role-specific page.

Updating the last login date

In a case specific bundles (FOSUserBundle, KnpUserBundle, …) aren't being used, the following code can update date and time after a user logs into the system.

The event security.interactive_login is fired upon a successful login. To perform actions after the login, you'll need to create a service in Resources\config\config.yml (or xml, php to your liking):

…
services:
acme.listener.login:
class: Acme\DemoBundle\Listener\UserLogin
arguments: [ @doctrine, @service_container ]
  tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onLogin }
…
<?php
namespace Acme\DemoBundle\Listener;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Acme\DemoBundle\Entity\User;
class UserLogin
{
protected $doctrine;
protected $container;
public function __construct(\Doctrine\Bundle\DoctrineBundle\Registry $doctrine, $container )
{
$this->doctrine = $doctrine;
$this->container = $container;
}
public function onLogin(InteractiveLoginEvent $event)
{
$entityManager = $this->doctrine->getManager();
$user = $this->container->get('security.context')->getToken()->getUser(); // getting the user
$user->setLastLogin(new \DateTime()); //updating data of the last login
//can apply any actions to the logged in user
$entityManager->flush(); //saving data
}
}

The class for updating last login date is ready. Try to log into the system and check the updated information in the database.

Redirecting a user to the role-specific page

For this example we'll need two roles: ROLE_USER and ROLE_ADMIN. Regular users should be redirected to the site root and the administrators should be redirected to the admin control panel.

As in the first example, let's subscribe to the security.interactive_login event.

…
services:
main.listener.login:
class: Acme\DemoBundle\Listener\UserLogin
arguments: [ @router, @security.context, @event_dispatcher ]
  tags:
 - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }
…

Now let's implement Acme\DemoBundle\Listener\UserLogin.php

<?php
namespace Acme\DemoBundle\Listener;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
class UserLogin
{
protected $router;
protected $security;
protected $dispatcher;
public function __construct(Router $router, SecurityContext $security, EventDispatcher $dispatcher)
{
$this->router = $router;
$this->security = $security;
$this->dispatcher = $dispatcher;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($this,'onKernelResponse'));
}
public function onKernelResponse(FilterResponseEvent $event)
{
if ($this->security->isGranted('ROLE_ADMIN')){
$response = new RedirectResponse($this->router->generate('admin'));
} else {
$response = new RedirectResponse($this->router->generate('index'));
}
$event->setResponse($response);
}
}

This code will redirect users according to the plan after the event is fired. Check the official documentation for the Symfony 2 framework for more details.

VN:F [1.9.22_1171]
Rating: 4.7/5 (15 votes cast)
VN:F [1.9.22_1171]
Rating: +5 (from 5 votes)
How to Work With Events in Symfony 2 Framework, 4.7 out of 5 based on 15 ratings



Request a Free Quote
 
 
 

Please enter the result and submit the form

Content created by Alexey Romanenko