您如何从 Symfony2 中的服务访问用户会话? [英] How do you access a users session from a service in Symfony2?
问题描述
有人知道如何访问服务中的会话变量吗?
Does anyone know how to access the session variable in a service?
我有一个服务设置,我将容器传递给它.我可以使用以下方法访问 Doctrine 服务之类的东西:
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
服务是的类实例SymfonyComponentHttpFoundationSession
,因此您应该能够检索具有该名称的会话:
php app/console container:debug
shows that the session
service is a class instanceof SymfonyComponentHttpFoundationSession
, 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
SymfonyComponentHttpFoundationSessionStorageNativeSessionStorage
session_listener
SymfonyBundleFrameworkBundleEventListenerSessionListener
这篇关于您如何从 Symfony2 中的服务访问用户会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!