How do you access a users session from a service in Symfony2?

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

}

Try this solution:

use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->get('variable');

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

Tags:

Php

Symfony