PHPnews.io

New in Symfony 5.3: Session Service Deprecation

Written by Symfony blog / Original link on May. 5, 2021

cd85bcae-d83d-4e2a-b7d8-2609eb653d81.png

Contributed by
Jérémy Derussé
in #38616.

In Symfony applications you can access the session via the session service or its SessionInterface autowiring alias. This is convenient, but it’s technically wrong for some reasons:

That’s why, many years after it was first proposed, we’re deprecating the session service in Symfony 5.3 and we’ll remove it in Symfony 6.0. Instead of injecting that session service you now have to inject the RequestStack service and use the new getSession() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\HttpFoundation\RequestStack;

class SomeService
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function someMethod()
    {
        $session = $this->requestStack->getSession();
        // ... do something with the session
    }

    // ...
}
Sponsor the Symfony project.

symfony

« PHPStan Generics for Dummies - With 2 Parents - ★ Develop faster by adding dev routes file in a Laravel app »