Adam Stacey Adam Stacey - 3 months ago 14x
PHP Question

How do you access a users session from a service in 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.

Any help would be really appreciated.


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');

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: instanceof Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage

session_listener instanceof Symfony\Bundle\FrameworkBundle\EventListener\SessionListener