Symfony2 - 重定向到登录页面时的Flash消息

时间:2014-06-16 09:45:27

标签: php symfony login addeventlistener flash-message

访问路径/ user / * 时,我在登录页面上有自动重定向。 我需要在重定向到登录页面时显示flash消息。

我读了一些关于事件监听器的内容,但需要一个真实的例子来实现它。

我在尝试:

services:
    listener.requestresponse:
        class: SciForum\Version2Bundle\EventListener\ExceptionListener
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

我的ExceptionListener

class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
    // You get the exception object from the received event
    $exception = $event->getException();
    $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
    );

    // Customize your response object to display the exception details
    $response = new Response();
    $response->setContent($message);

    // HttpExceptionInterface is a special type of exception that
    // holds status code and header details
    if ($exception instanceof HttpExceptionInterface) {
        $response->setStatusCode($exception->getStatusCode());
        $response->headers->replace($exception->getHeaders());
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    // Send the modified response object to the event
    $event->setResponse($response);
}
}

但是当自动重定向出现时,例外是新的抛出。

1 个答案:

答案 0 :(得分:0)

EventListener旨在侦听特定事件。您已经创建了一个ExceptionListener,它将GetResponseForExceptionEvent作为参数。如果重定向成功,那么它将不会抛出任何异常。

您需要创建一个通用的EventListener,甚至是InteractiveLoginEvent listener:

这是我做的登录监听器:

    use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
    use Symfony\Component\Security\Core\SecurityContext;
    use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; 

class LoginListener
{

    private $securityContext;       

    private $em;        

    public function __construct(SecurityContext $securityContext, Doctrine $doctrine)
    {
        $this->securityContext = $securityContext;
        $this->em              = $doctrine->getManager();
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
             //do stuff
    }
}

但是,要直接解决您的问题,您是否只能在控制器中获取重定向标题然后显示消息?

相关问题