我有一个注销侦听器,我想在其中设置一条显示注销确认消息的闪存消息。
namespace Acme\MyBundle\Security\Listeners;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LogoutListener implements LogoutSuccessHandlerInterface
{
private $security;
public function __construct(SecurityContext $security)
{
$this->security = $security;
}
public function onLogoutSuccess(Request $request)
{
$request->get('session')->getFlashBag()->add('notice', 'You have been successfully been logged out.');
$response = new RedirectResponse('login');
return $response;
}
}
这是我的 services.yml(与此相关):
logout_listener:
class: ACME\MyBundle\Security\Listeners\LogoutListener
arguments: [@security.context]
这会产生错误:
Fatal error: Call to a member function getFlashBag() on a non-object
如何在这种情况下设置 flashBag 消息?
另外,如何访问路由器,以便生成 url(通过 $this->router->generate('login'))而不是传入硬编码的 url?
分辨率说明
要让 flash 工作,您必须告诉您的 security.yml 配置不要在注销时使会话无效;否则,会话将被破坏,您的闪存将永远不会出现。
logout:
path: /logout
success_handler: logout_listener
invalidate_session: false