Symfony Request Attributes

If you're working with the Symfony framework the chances are at some stage you've worked with the Request class from the http-foundation component.

The chances are that to get route parameters you've done something close to the following

<?php

namespace Demo\Controller;

use Symfony\Component\HttpFoundation;


public function controllerAction(Request $request)
{
  $routeParam = $request->get('route_key');
}

This code is really simple to understand and use, but it means that under the hood Symfony is having to check query strings, post variables and route attributes to get that one parameter, which is not ideal from a speed perspective (note: the difference will be milliseconds, not much of a concern to many people).

This week I learned the easy way to pick up route parameters (in what I believe is a quicker, and definitely more explicit way)

<?php

namespace Demo\Controller;

use Symfony\Component\HttpFoundation;


public function controllerAction(Request $request)
{
  $routeParam = $request->attributes->get('route_key');
}

Using the attributes property from the request we have told the Request class to get pre-set keys managed by the route (or any middleware class) rather than using the common query or post attributes

Categories: code, php, symfony, snippets