In Symfony, the HTTP request is represented by the Request object. It contains all information about the current request, such as query parameters, headers, session data, locale, and more. This tutorial demonstrates how to get Request object in Symfony 8 application.
Controller
The most straightforward way to work with the request in a controller is to type-hint the Request class in the action method. Symfony will automatically inject the current request for you.
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
{
return new Response($request->getLocale());
}
}
Service
Unlike controllers, services do not automatically receive the current Request. There are two common ways to work with it inside a service.
The first option is to pass the Request object directly to the method that needs it. This keeps the service independent of the HTTP layer.
The second option is to inject the RequestStack service. This allows the service to fetch the currently active request using the getCurrentRequest method when needed.
src/Service/TestService.php
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
class TestService
{
public function __construct(private RequestStack $requestStack)
{
}
public function getLocale(): ?string
{
$request = $this->requestStack->getCurrentRequest();
return $request?->getLocale();
}
}
Template
Inside Twig templates, Symfony exposes the current request through the global app variable. This makes it easy to read request data directly in the templates.
templates/test/index.html.twig
{{ app.request.locale }}
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController extends AbstractController
{
#[Route('/')]
public function index(): Response
{
return $this->render('test/index.html.twig');
}
}
Leave a Comment
Cancel reply