我试图在用户登录FOSUserBundle后执行一个函数,在我的config.yml中我设置了服务:
services:
authentication.success.listener:
class: MyCompany\MyBundle\EventListener\AuthenticationEventListener
arguments: [@router]
tags:
- { name: kernel.event_subscriber }
然后,我用方法创建Listener类:
<?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...
}
}
?>
当我尝试登录时,之后没有任何反应,我写了一些错误的代码来生成异常,但一切顺利......显然这个功能并没有被排除在外。
请帮忙吗?
答案 0 :(得分:6)
好吧,最后几个小时搜索并享受尤文图斯战胜皇家马德里队(2-1)后,我找到了一个解决方案。我的解决方案是修改&#39; success_handler&#39;在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;
}
}
?>
我希望它对你们有用......
非常感谢!
答案 1 :(得分:0)
试试这段代码:
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::SECURITY_IMPLICIT_LOGIN => array('onAuthenticationnSuccess',0)
);
}
这应该是这里记录的语法:http://symfony.com/doc/current/components/event_dispatcher/introduction.html