2015-05-05 4 views
0

Я пытаюсь выполнить функцию после входа пользователя в FOSUserBundle, в моем config.yml я поставил службу:Выполнение функции после Пользователь Логин Symfony 2,3

services: 
    authentication.success.listener: 
     class: MyCompany\MyBundle\EventListener\AuthenticationEventListener 
     arguments: [@router] 
     tags: 
      - { name: kernel.event_subscriber } 

Затем я создаю класс прослушивателя с методами :

<?php 

namespace MyCompany\MyBundle\EventListener; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; 
use FOS\UserBundle\FOSUserEvents; 
use FOS\UserBundle\Event\UserEvent; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Cookie as Cookie; 

class AuthenticationEventListener implements EventSubscriberInterface 
{  
    private $router; 

    public function __construct(UrlGeneratorInterface $router) 
    { 
     $this->router = $router; 
    } 

    public static function getSubscribedEvents() 
    { 
     return array(
       FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'onAuthenticationSuccess', 
     ); 
    } 

    public function onAuthenticationSuccess(UserEvent $event) 
    { 
     //my actions goes here... 
    } 

} 

?> 

При попытке войти в систему, ничего не происходит после того, как я пишу некоторые неправильный код для генерации исключения, но все идет хорошо ... по-видимому, эта функция не excetuted.

Любая помощь пожалуйста?

ответ

0

Попробуйте этот код:

public static function getSubscribedEvents() 
{ 
    return array(
     FOSUserEvents::SECURITY_IMPLICIT_LOGIN => array('onAuthenticationnSuccess',0) 
    ); 
} 

Это должно быть синтаксис любил документированный здесь: http://symfony.com/doc/current/components/event_dispatcher/introduction.html

+0

Извините, ребята, в функции есть опечатка, он должен сказать: onAuthenticationSuccess (single n). Я исправил в своем коде, но все равно не работаю. Любая идея, что происходит? Благодаря! – relez

3

Ну, наконец, после поиска несколько часов и наслаждаясь победой над Ювентусом Реалом (2-1) I нашел решение. Мое решение состоит в модификации «success_handler» в security.yml и создать событие, это код:

security: 
    .. 
    firewalls: 
     main: 
     .. 
     success_handler: authentication.success.listener 

Тогда в services.yml Объявляю службу:

services: 
    authentication.success.listener: 
     class: MyCompany\MyBundle\EventListener\AuthenticationEventListener 
     arguments: ['@router', '@security.context', '@service_container'] 

Тогда я объявляю класс/функция для прослушивания:

// MyCompany\MyBundle\EventListener\AuthenticationEventListener.php 

<?php 

namespace MyCompany\MyBundle\EventListener; 

use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; 
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; 
use Symfony\Component\Security\Core\SecurityContext; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\Routing\Router;  

class AuthenticationEventListener implements AuthenticationSuccessHandlerInterface 
{  
    protected $router; 
    protected $security; 
    protected $container; 
    protected $em; 

    public function __construct(Router $router, SecurityContext $security, $container) 
    { 
     $this->router = $router; 
     $this->security = $security; 
     $this->container = $container; 
     $this->em = $this->container->get('doctrine')->getEntityManager(); 
    } 

    public function onAuthenticationSuccess(Request $request, TokenInterface $token) 
    { 
     $response = new Response(); 
     $response = new RedirectResponse('dashboard'); 
     return $response; 
    } 

} 

?> 

Я надеюсь, что это может быть полезно для вас, ребята ...

Спасибо в любом случае!

+0

wha "АутентификацияSuccessHandlerInterface" –

Смежные вопросы