Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are exactly $request->attributes?

I´m very new to php and I don´t quite understand how the attributes are saved in $request.

We´re working with a class Controller.php, which contains every function that transfer the data to the html.twig; a class Model.php, which contains every functions with the queries to get the data from the database; and we work with Twig templates for the html part.

I know, that if I want to get the attributes of 'user' I have to write:

$request->attributes->get('user'), because in there there is an array 'user' with the parameters 'username', 'password' etc.

But how does this attribute 'user' (or whatever parameter) get to be in $request? I need to access to more data through the attributes, but first I have to know how they are saved there.

Thanks!

like image 919
bonishadelnorte Avatar asked Aug 31 '25 05:08

bonishadelnorte


1 Answers

attribues is the only parameter bag of the Symfony Request object that's populated by the application. All the other parameter bags, like request, query, server, are populated with the http request data.

attributes can be populated at any point of the application lifecycle, but most of the time it will be done in a kernel.request event listener. Docs explain more about event listeners and built in Symfony Kernel events in case you haven't used them yet.

The idea behind the kernel.request event is that it's called before the controller. It's perfect for implementing code that's suppose to be called for all your requests. For example, this is the way the built in RouterListener adds route path parameters as request attributes. So if the path is /foo/{bar} you're able to access path placeholders with $request->attributes->get('bar'). What happens in the RouteListener is:

// $parameters contains route path placeholders
$request->attributes->add($parameters);
unset($parameters['_route'], $parameters['_controller']);
$request->attributes->set('_route_params', $parameters);

If you'd like to add more attributes to your request you'll need to implement your own event listener. Once you register it, Symfony will call it automatically and your attributes will be populated.

like image 152
Jakub Zalas Avatar answered Sep 02 '25 19:09

Jakub Zalas