I'm a little confused as to the "right" way to retrieve the current session object within a controller in Symfony 5.3. The current documentation says to typehint an argument as SessionInterface
. However, this Symfony blog post says SessionInterface
has been deprecated in favor of using RequestStack
.
In services it's clear that I should inject RequestStack
and call $requestStack->getSession()
. However, in most controller methods I'm already injecting the Request
object which also has a getSession()
method that seems to work.
Is it okay to get the session from the Request
object, or should I inject RequestStack
in addition to Request
in my controller methods (this feels like duplication almost)
A quick code example:
// in a controller
public function myRoute(Request $request): Response
{
$session = $request->getSession(); // this works
}
// seems silly to also inject RequestStack when I already have Request
public function myRoute(Request $request, RequestStack $requestStack): Response
{
$reqestStack->getSession(); // this works
}
// the way current documentation shows
public function myRoute(Request $request, SessionInterface $session): Response
{
// this causes a deprecation warning from injecting SessionInterface
}
HttpFoundation
component, yet theRequestStack
is part of that component. Looking into theRequestStack::getSession()
source code, all it's really doing is callingRequest::getSession()
anyway, so it feels like a wrapper/convenience method to me more than anything else. The docs definitely need some updating, I'll look into opening a PR for this. Thanks for the reply. – Hamrah