Skip to content
Konrad Alfaro

Symfony Request Tip

Symfony1 min read

Working with Symfony's Request object

Let's say you've got an UI action like this one in you application:

1<?php
2
3declare(strict_types=1);
4
5namespace App\Ui;
6
7use Symfony\Component\HttpFoundation\Request;
8
9final class ListProductsAction
10{
11 // ...
12
13 public function __invoke(Request $request): Response
14 {
15 $categoryId = $request->get('categoryId');
16
17 // Some actions are taking place and then you return a Response
18 }
19}

The code above is a simple controller with a purpose of listing some products by categoryId (it follows the ADR approach - I will cover this topic in next posts 😉). But wait! What exactly is categoryId in $request->get('categoryId')? Actually, Symfony "helps you" by allowing you to do not care about the origin of it. And this is bad. 💔

Why is it bad?

  • Readability - one of best practices for writing controllers is to store your routing configuration away from class that handles the route. In our example code, the configuration would be covered in some XML file. So actually we don't know how does our route looks like. It can be a route with some attributes expected /products/{categoryId}/{subCategoryId}, it can be a POST route expecting a request body or it can expect some additional GET parameters.
  • "Optimization" - I put this in quotations because it won't affect the performance at all, but just look what does the Request::get() method. It has way too complex logic for such a simple operation like getting a data from request. Especially, when we should know what our requests are and do.

How can we improve?

Don't worry, it's simple! Just use suitable properties from Request object. You can use:

1// /your/path/{your-attribute}/{another-attribute}
2$request->attributes->get('your-attribute') // value under your-attribute

Fetching from attributes from the URL

1// /your/path/?{your-parameter}=some-value`
2$request->query->get('your-parameter') // some-value

Fetching from query to get extra values from your URL

1$request->request->get('your-parametr')

Fetching from request to get a request body ($_POST)

Each Request attribute is a ParameterBag instance so you don't need to change anything except adding a property:

1-$categoryId = $request->get('categoryId');
2+$categoryId = $request->attribute->get('categoryId');

I know this post is not a breaking change in your thinking about software development. It's a simple tip, just as the title suggests! But remember - Your never work alone on the code. So make it readable for others. 😉