New in Symfony 5.3: Session Service Deprecation

Symfony 5.3 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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:
- Session is a data object (e.g. like the Request object) so there shouldn't be a service defined for it in the container;
- Sessions are not part of the HTTP specification (either HTTP/1.1, HTTP/2 or HTTP/3) because HTTP is stateless. That's why it feels odd to handle sessions as part of the HttpFoundation component.
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
}
// ...
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
"Session is a data object and there should be no definition for it in the container": true, but so are Request and RequestStack. If we're saying that session must be removed, then RequestStack is also not a correct abstraction.
"Handling sessions as part of the HTTP foundation feels weird": well yeah, but how does forcing to go though the RequestStack (which is also part of the HTTP foundation) fix this? I don't really think it does.
This to me feels like swapping one mistake for another. If we agree that data objects should not live in the container, then perhaps we should change the session abstraction from entity-like to repository-like, so the communication is done though a service that "does" something instead of an object that "is" something.
Because I fear this comment might get lost, I'll also write something on GitHub, so I already apologize for the repetition.