有人知道如何访问服务中的 session 变量吗?
我有一个服务设置,我将容器传递给它。我可以通过以下方式访问 Doctrine 服务之类的东西:
// Get the doctrine service
$doctrine_service = $this->container->get('doctrine');
// Get the entity manager
$em = $doctrine_service->getEntityManager();
但是,我不确定如何访问 session 。
在 Controller 中,可以使用以下方式访问 session :
$session = $this->getRequest()->getSession();
$session->set('foo', 'bar');
$foo = $session->get('foo');
session 是服务的一部分吗?如果是,服务的名称是什么。
任何帮助将不胜感激。
最佳答案
如果您不想传入整个容器,只需在参数中传入@session:
services.yml
my.service:
class: MyApp\Service
arguments: ['@session']
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');
}
}
关于php - 您如何从 Symfony2 中的服务访问用户 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7192916/