Symfony 2 - 在Controller外部设置Flash消息

dor*_*emi 15 symfony

我有一个注销侦听器,我想在其中设置一条显示注销确认消息的flash消息.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的services.yml(因为它与此有关):

logout_listener:
   class:  ACME\MyBundle\Security\Listeners\LogoutListener
   arguments: [@security.context]
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

Fatal error: Call to a member function getFlashBag() on a non-object
Run Code Online (Sandbox Code Playgroud)

如何在此上下文中设置flashBag消息?

另外,如何访问路由器以便我可以生成URL(通过$ this-> router-> generate('login'))而不是传入硬编码的URL?

决议说明

要使闪存工作,您必须告诉security.yml配置在注销时不会使会话失效; 否则,会话将被销毁,您的闪存将永远不会出现.

logout:
    path: /logout
        success_handler: logout_listener
        invalidate_session: false
Run Code Online (Sandbox Code Playgroud)

Ald*_*nio 26

您应该将会话和路由器的服务注入LogoutListener并使用它们来执行这些任务.这是在yml中执行此操作的方法:

logout_listener: 
class: ACME\MyBundle\Security\Listeners\LogoutListener 
arguments: [@security.context, @router, @session]
Run Code Online (Sandbox Code Playgroud)

然后在你的课上你写:

class LogoutListener implements LogoutSuccessHandlerInterface
{
    private $security;
    private $router;
    private $session;

    public function __construct(SecurityContext $security, Router $router, Session $session)
    {
        $this->security = $security;
        $this->router = $router;
        $this->session = $session;
    }
    [...]
Run Code Online (Sandbox Code Playgroud)

当你想现在使用会话时,你可以说:

$this->session->getFlashBag()->add('notice', 'You have been successfully been logged out.');
Run Code Online (Sandbox Code Playgroud)

同样,您可以使用路由器服务生成路由.