Symfony 2 – 在Controller外设置Flash消息

前端之家收集整理的这篇文章主要介绍了Symfony 2 – 在Controller外设置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;
  }
}

这是我的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?

分辨率说明

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

logout:
    path: /logout
        success_handler: logout_listener
        invalidate_session: false

解决方法

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

logout_listener: 
class: ACME\MyBundle\Security\Listeners\logoutListener 
arguments: [@security.context,@router,@session]

然后在你的课上写:

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;
    }
    [...]

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

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

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

猜你在找的Flash相关文章