Reference / Symfony
/

Routing

Maps incoming URLs to controller methods. Compiled to a fast PHP matcher so lookup is constant-time-ish.

Foundational
  • Define routes via `#[Route]` attributes on controller methods (preferred), or YAML/XML.
  • Route parameters: `/users/{id}`. Add `requirements` (regex) and `defaults` to constrain.
  • Param converters auto-resolve entities: type-hint `User $user` and Symfony fetches it by id from the URL.
  • Generate URLs in PHP with `$urlGenerator->generate('route_name', ['id' => 5])`; in Twig with `{{ path(...) }}`.
  • Routes are matched in declaration order — put more specific routes first.
  • `bin/console debug:router` lists every route with its path, method, and controller.
#[Route('/users/{id}', name: 'app_user_show', requirements: ['id' => '\d+'], methods: ['GET'])]
public function show(User $user): Response
{
    return $this->render('user/show.html.twig', ['user' => $user]);
}

Common gotchas

  • Trailing slashes matter. `/users` and `/users/` are different routes unless you configure a trailing-slash redirect.
  • Param converters silently 404 if the entity does not exist. That is usually what you want, but worth knowing.