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
}
// ...
}
Niceee 🌟🌟🌟
Does the SessionValueResolver from HttpKernel still remain?
Good news and great work!
While I also don't really like the current use of the session, how is the new approach any better, given the motivations?
"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.
Thanks for your comments @Davide. Indeed you are right and it's better to move this discussion to GitHub because it will be easier to discuss and follow. Thanks!
This change is the first step towards a better session management system. Injecting a session might lead to problems when using sub-requests for instance; injecting the request stack solves this issue as you always get the right session instance. One next step could be to create a new dedicated session component to extract it from HttpFoundation. Anyway, let's move the discussion to Github.
Great to see this change on the board :)