[Symfony] Get the parameters of the current route
Published on 2018-12-11 • Modified on 2018-12-11
These two magic variables are available in controllers' actions. We can declare them as function parameters or we can retrieve them from the request's attributes ($request->attributes->get()
). I use them regularly to generate breadcrumbs. Fun fact: if using $_route_params
as a function parameter, PHP_CodeSniffer will raise an error:
54 | ERROR | [ ] Variable "_route_params" is not in valid camel caps format
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
use Symfony\Component\HttpFoundation\Request;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet9Trait
{
public function snippet9(Request $request): void
{
$route = $request->attributes->get('_route');
$params = $request->attributes->get('_route_params');
// Or you can use TypeHint directly in your controller function
// public function snippet9(string $_route, array $_route_params)
echo $route.PHP_EOL;
print_r($params); // That's it! 😁
}
}
Run this snippet More on Stackoverflow Random snippet