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:debugshows that thesessionservice is a class instanceofSymfony\Component\HttpFoundation\Session, so you should be able to retrieve the session with that name: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.storageinstanceofSymfony\Component\HttpFoundation\SessionStorage\NativeSessionStoragesession_listenerinstanceofSymfony\Bundle\FrameworkBundle\EventListener\SessionListener