Categories
Web Development

Symfony 5.3+ how to use Sessions with RequestStack

So some changes happened in Symfony 5.3. Previously you could get to a session with either Session or SessionInterface. Some didn’t like how that worked so now it is moved to RequestStack. The docs or article are not correct here.

It shows you get to the session like this.


$session = $this->requestStack->getSession();

But that doesn’t work. You will be told that RequestStack doesn’t have a getSession() method. I had to open up the source code to figure out how this works.

You get to the session instead like this now.


 $session = $this->requestStack->getCurrentRequest()->getSession();

Note you have to call getCurrentRequest() then getSession. now you can use sessions like this.


$session = $this->requestStack->getCurrentRequest()->getSession();
        $session->set('key-name', $value);

You will now have access to all of the session methods via $session. Your IDE should now list all of the methods in the Session class that you can access.

How to get the RequestStack?

So how do you get the ReqeustStack? Autowiring.

You simply Autowire it into your Controller route method or the __constructor() method. I prefer the constructor method in my Controllers if more than one route needs it.  But in other services you have no choice, it has to be autowired via the constructor like this.



   private RequestStack $requestStack;

    public function __construct(MysqlConnection $mysqlConnection, RequestStack $requestStack)
    {
        $this->mysqlConnection = $mysqlConnection;
        $this->illegalRequest = 'Sorry. Your request to this API is not allowed';
        $this->requestStack = $requestStack;
    }

Now any method can access the requestStack and through the RequestStack you can access the Session. At least for now.

Here is a link to the actual Symfony Session docs.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.