— Symfony — 1 min read
Request
objectLet's say you've got an UI action like this one in you application:
1<?php23declare(strict_types=1);45namespace App\Ui;67use Symfony\Component\HttpFoundation\Request;89final class ListProductsAction10{11 // ...12 13 public function __invoke(Request $request): Response14 {15 $categoryId = $request->get('categoryId');16 17 // Some actions are taking place and then you return a Response18 }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. 💔
/products/{categoryId}/{subCategoryId}
, it can be a POST
route expecting a request body
or it can expect some
additional GET
parameters.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 request
s are and do.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. 😉