加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Symfony 2 – 在Controller外设置Flash消息

发布时间:2020-12-15 07:33:59 所属栏目:百科 来源:网络整理
导读:我有一个注销侦听器,我想设置一个闪烁的消息,显示一个注销确认消息. namespace AcmeMyBundleSecurityListeners;use SymfonyComponentSecurityHttpLogoutLogoutSuccessHandlerInterface;use SymfonyComponentSecurityCoreSecurityContext;use Sym
我有一个注销侦听器,我想设置一个闪烁的消息,显示一个注销确认消息.

namespace AcmeMyBundleSecurityListeners;

use SymfonyComponentSecurityHttpLogoutLogoutSuccessHandlerInterface;
use SymfonyComponentSecurityCoreSecurityContext;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationRedirectResponse;

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:  ACMEMyBundleSecurityListenersLogoutListener
   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: ACMEMyBundleSecurityListenersLogoutListener 
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.');

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读