Symfony默认会话变量

时间:2016-04-07 14:41:46

标签: php symfony

你能帮助我吗?如何在预初始化框架中设置会话中的默认变量,而不是在某些控制器中?感谢

1 个答案:

答案 0 :(得分:1)

Symfony有一些事件可以附加您自己的event listener。您可以附加事件监听器的那个将是kernel.request。以下是您可以使用的示例源代码

首先,在services.yml文件夹下的Resources/config文件中:

services:
  listener.my_request_listener:
    class: My\AwesomeBundle\Listener\MyListener
    arguments: [ @session ]
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

其次,您的MyListener将如下所示:

namespace My\AwesomeBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session;

class MyListener
{
    protected $session;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $kernel    = $event->getKernel();
        $request   = $event->getRequest();
        //Your logic goes here
        if($this->session->has('someKey')){
            $this->session->set('someKey','newvalue');
        }
    }
}