如何通过Symfony2中的服务访问用户会话? [英] How do you access a users session from a service in Symfony2?

查看:52
本文介绍了如何通过Symfony2中的服务访问用户会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to access the session variable in a service?

我有一个将容器传递给的服务设置.我可以使用以下方式访问诸如教义"服务之类的东西:

I have a service setup that I pass the container over to. I can access things like the Doctrine service by using:

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

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

However, I'm not sure how to access the session.

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

In a controller the session can be accessed using:

$session = $this->getRequest()->getSession();
$session->set('foo', 'bar');
$foo = $session->get('foo');

是服务的会话部分,如果是的话,服务称为什么.

Is the session part of a service and if so what is the service called.

任何帮助将不胜感激.

推荐答案

php app/console container:debug显示session服务是Symfony\Component\HttpFoundation\Session的类实例,因此您应该能够使用以下名称检索会话:

php app/console container:debug shows that the session service is a class instanceof Symfony\Component\HttpFoundation\Session, so you should be able to retrieve the session with that name:

$session = $this->container->get('session');

在会话中完成工作后,请调用$session->save();将所有内容写回到会话中.顺便说一句,我的容器转储中还显示了其他两个与会话相关的服务:

After you've done your work on the session, call $session->save(); to write everything back to the session. Incidentally, there are two other session-related services that show in my container dump, as well:

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

session_listener Symfony\Bundle\FrameworkBundle\EventListener\SessionListener

这篇关于如何通过Symfony2中的服务访问用户会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆