当访问路由/user/*时,我在登录页面上自动重定向。我需要在重定向到登录页面时显示一个flash消息。
我读了一些关于事件监听器的东西,但需要一个真实的例子来实现它。
I was trying:
services:
listener.requestresponse:
class: SciForumVersion2BundleEventListenerExceptionListener
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);
}
}
但是当自动重定向存在时,异常是较新的抛出。
EventListener被设计用来监听特定的事件。您已经创建了一个ExceptionListener,它将GetResponseForExceptionEvent作为参数。如果重定向成功,那么它永远不会抛出任何异常。
你需要创建一个通用的EventListener,或者甚至一个InteractiveLoginEvent listener:
这是我做的一个登录监听器:
use SymfonyComponentSecurityHttpEventInteractiveLoginEvent;
use SymfonyComponentSecurityCoreSecurityContext;
use DoctrineBundleDoctrineBundleRegistry 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
}
}
但是,要直接解决您的问题,您可以不只是在控制器中获得重定向头,然后显示消息吗?