如何从Symfony2中的服务访问用户会话?

Ada*_*cey 34 php symfony

有谁知道如何访问服务中的会话变量?

我有一个服务设置,我将容器传递给.我可以使用以下方法访问Doctrine服务之类的内容:

// Get the doctrine service
$doctrine_service = $this->container->get('doctrine');  
// Get the entity manager
$em = $doctrine_service->getEntityManager();
Run Code Online (Sandbox Code Playgroud)

但是,我不确定如何访问会话.

在控制器中,可以使用以下方式访问会话:

$session = $this->getRequest()->getSession();
$session->set('foo', 'bar');
$foo = $session->get('foo');
Run Code Online (Sandbox Code Playgroud)

会话是服务的一部分,如果是,那么所调用的服务是什么.

任何帮助将非常感激.

gre*_*reg 57

如果您不想传入整个容器,只需在参数中传入@session:

services.yml

my.service:
    class: MyApp\Service
    arguments: ['@session']
Run Code Online (Sandbox Code Playgroud)

Service.php

use Symfony\Component\HttpFoundation\Session\Session;

class Service
{

    private $session;

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

    public function someService()
    {
        $sessionVar = $this->session->get('session_var');
    }

}
Run Code Online (Sandbox Code Playgroud)


Pro*_*tic 28

php app/console container:debug显示该session服务是一个类instanceof Symfony\Component\HttpFoundation\Session,因此您应该能够检索具有该名称的会话:

$session = $this->container->get('session');
Run Code Online (Sandbox Code Playgroud)

完成会话后的工作后,调用$session->save();将所有内容写回会话.顺便提一下,我的容器转储中还有两个与会话相关的服务:

session.storage 的instanceof Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage

session_listener 的instanceof Symfony\Bundle\FrameworkBundle\EventListener\SessionListener

  • 我检查了Session类,它有一个`save()`方法.试试一下,看看它是否适合你. (2认同)