Php Symfony2-重定向到登录页面时闪烁消息
当访问route/user/*时,我在登录页面上有自动重定向。 我需要在重定向到登录页面时显示flash消息 我读了一些关于事件侦听器的内容,但需要一个真正的示例来实现它 我试着:Php Symfony2-重定向到登录页面时闪烁消息,php,symfony,login,addeventlistener,flash-message,Php,Symfony,Login,Addeventlistener,Flash Message,当访问route/user/*时,我在登录页面上有自动重定向。 我需要在重定向到登录页面时显示flash消息 我读了一些关于事件侦听器的内容,但需要一个真正的示例来实现它 我试着: services: listener.requestresponse: class: SciForum\Version2Bundle\EventListener\ExceptionListener tags: - { name: kernel.event_l
services:
listener.requestresponse:
class: SciForum\Version2Bundle\EventListener\ExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
还有我的例外听众
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,甚至是一个 以下是我制作的登录侦听器:
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
}
}
但是,为了直接解决您的问题,您是否可以在控制器中获取重定向头,然后显示消息?重定向不会引发异常,因此我想这就是您的代码无法工作的原因。我将查看传递:而不是GetResponseForExceptionEvent@BobFlemming,你能详细解释一下你的评论吗。一个例子的答案将是完美的。非常感谢。