Php 如何从Symfony2中的服务访问用户会话?
有人知道如何访问服务中的会话变量吗 我有一个服务设置,我将容器传递给它。我可以通过以下方式访问条令服务:Php 如何从Symfony2中的服务访问用户会话?,php,symfony,Php,Symfony,有人知道如何访问服务中的会话变量吗 我有一个服务设置,我将容器传递给它。我可以通过以下方式访问条令服务: // Get the doctrine service $doctrine_service = $this->container->get('doctrine'); // Get the entity manager $em = $doctrine_service->getEntityManager(); 但是,我不确定如何访问会话 在控制器中,可通过以下方式访问会话
// Get the doctrine service
$doctrine_service = $this->container->get('doctrine');
// Get the entity manager
$em = $doctrine_service->getEntityManager();
但是,我不确定如何访问会话
在控制器中,可通过以下方式访问会话:
$session = $this->getRequest()->getSession();
$session->set('foo', 'bar');
$foo = $session->get('foo');
会话是服务的一部分,如果是,该服务被称为什么
非常感谢您的帮助。
php应用程序/控制台容器:debug
显示会话
服务是Symfony\Component\HttpFoundation\session
的类实例,因此您应该能够检索具有该名称的会话:
$session = $this->container->get('session');
完成会话工作后,调用$session->save()
将所有内容写回会话。顺便说一句,我的容器转储中还显示了另外两个与会话相关的服务:
session.storage
instanceofSymfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage
session\u listener
instanceofSymfony\Bundle\FrameworkBundle\EventListener\SessionListener
如果不想在整个容器中传递,只需在参数中传递@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');
}
}
尝试以下解决方案:
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->get('variable');
法兹·阿西姆·瓦伊函数
use Symfony\Component\HttpFoundation\Session\Session;
class ClassType extends AbstractType {
private $session;
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$this->session = new Session();
->add('field', $this->session->get('nameFieldSession'));
}
}
在Symfony 4中,如果将服务配置为自动连线,则不再需要通过
services.yaml
手动注入会话
相反,您只需注入会话接口:
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class SessionService
{
private $session;
public function __construct(
SessionInterface $session
)
{
$this->session = $session;
}
}
你好,谢谢你的快速回复。我尝试了
$session=$this->container->get('session')代码>虽然它工作了,但似乎没有将任何内容保存到会话中。我需要做些什么才能将更新的会话数据传回吗?我签出了会话类,它有一个save()
方法。试着打个电话,看看对你是否有用。天才!这是一种享受。谢谢你的帮助!因此,设置会话为$session=$this->getRequest()->getSession()$会话->设置('foo','bar')$会话->保存();在另一个控制器中检索会话是$session=$this->container->get('session')?你好我是SF2的新手,我正在尝试弄清楚会话是如何工作的。。请告诉我如何使用此服务设置或获取控制器中的会话?您好,您可以从控制器访问整个“服务容器”。因此,要获取会话,您可以执行$session=$this->container->get('session')代码>同样地,您需要的任何其他服务也可以通过同样的方式获得。当您只编写原始过程PHP时,从Symfony开始是很棘手的。我强烈建议你找到一个很好的教程,从开始到结束构建一个基本的应用程序,并完成这项工作,它将让你更好地了解应用程序的功能以及如何构建应用程序。很好,我是一名Laravel开发者,两个月前开始使用symfony时,情况大不相同。。更“复杂”,但谢谢你的建议!这是执行OP要求的更好的方法。与其直接尝试从服务访问会话对象,不如将其注入服务。我就是这样做的。请用英语写。