2 Methods to Get Session Object in Symfony 7

2 Methods to Get Session Object in Symfony 7

Symfony framework provides the Session object which can be used for storing information about the user between requests.

This tutorial provides 2 methods how to get Session object in Symfony 7 application.

Method 1 - Request class

We can access to the Session object by using getSession method of the Request class.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(Request $request): Response
    {
        $session = $request->getSession();

        return new Response($session->getName());
    }
}

Method 2 - RequestStack class

We can inject the RequestStack service and retrieve the Session object using getSession method.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class TestController
{
    public function __construct(private RequestStack $requestStack)
    {
    }

    #[Route('/')]
    public function index(): Response
    {
        $session = $this->requestStack->getSession();

        return new Response($session->getName());
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.