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.
However, if you have the following configuration, Symfony will store the session data in files in the cache directory %kernel. cache_dir%/sessions . This means that when you clear the cache, any current sessions will also be deleted: YAML.
Symfony provides a session object and several utilities that you can use to store information about the user between requests.
If you don't want to pass in the entire container you simply pass in @session in the arguments:
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');
}
}
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:
session.storage
instanceof Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage
session_listener
instanceof Symfony\Bundle\FrameworkBundle\EventListener\SessionListener
In Symfony 4, if you have your services configured to autowire you do not need to inject the session manually through services.yaml
any longer.
Instead you would simply inject the session interface:
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class SessionService
{
private $session;
public function __construct(
SessionInterface $session
)
{
$this->session = $session;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With