Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 62 ยท Routing and Controllers

Routing with Attributes

Learn how the Symfony #[Route] attribute maps URLs to controllers - path, name, methods, requirements, defaults, host, priority and class-level prefixes.

A route connects a URL to a piece of code. When a request for /blog/hello-world arrives, Symfony's Routing component looks through all known routes, finds the first one that fits, and tells the kernel which controller to call. Almost every Symfony application defines its routes with the #[Route] attribute, written directly above the controller method it belongs to.

In Your First Page you wrote a single route. This lesson covers everything the attribute can say: the path, the route name, the allowed HTTP methods, requirements, defaults, host matching and priority. You will also see how to put shared settings on the controller class instead of repeating them. The examples that run here use a small stand-in router that reads real PHP attributes through reflection, which is exactly the trick Symfony itself uses.

The #[Route] attribute

The attribute lives in the Symfony\Component\Routing\Attribute\Route namespace (older projects use Annotation instead of Attribute). Its first argument is the path; everything else is a named argument:

PHP
// src/Controller/BlogController.php (real Symfony, read-only)
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class BlogController
{
    #[Route('/blog', name: 'blog_index', methods: ['GET'])]
    public function index(): Response
    {
        return new Response('All posts');
    }
}

Symfony only scans your controllers if you tell it where they are. The recipe for the framework bundle adds this file for you:

YAML
# config/routes.yaml (real Symfony, read-only)
controllers:
    resource:
        path: ../src/Controller/
        namespace: App\Controller
    type: attribute

At build time Symfony loads each class in that directory, reads the #[Route] attributes, and turns them into one big route collection. In production this collection is compiled into a fast matcher and cached, so reading attributes costs nothing per request.

flowchart LR
    A["src/Controller/*.php"] --> B["Attribute loader<br/>(reads #[Route])"]
    B --> C["RouteCollection"]
    C --> D["Compiled matcher<br/>(cached in var/cache)"]
    R["Request /blog"] --> D
    D --> E["_controller + parameters"]

Attributes are read once into a route collection, which is compiled and cached; each request only runs the compiled matcher.

What the attribute can express

Here are the options you will use most often.

Option Example Meaning
path (first argument) '/blog/{slug}' The URL pattern; is a placeholder
name 'blog_show' Unique id used to generate URLs
methods ['GET', 'HEAD'] Allowed HTTP methods; others get a 405 response
requirements ['page' => '\d+'] A regular expression each placeholder must satisfy
defaults ['page' => 1] Values used when a placeholder is missing
host 'admin.example.com' Only match on this host name
schemes ['https'] Only match this scheme
priority 10 Higher numbers are tried earlier
condition "request.headers.get('X-Api') == '1'" An expression that must be true
stateless true The route needs no session, so responses can be cached

A route with several of them at once looks like this:

PHP
// real Symfony, read-only
#[Route(
    path: '/blog/page/{page}',
    name: 'blog_list',
    requirements: ['page' => '\d+'],
    defaults: ['page' => 1],
    methods: ['GET'],
)]
public function list(int $page): Response
{
    // ...
}

Two things to remember. First, a route name must be unique across the whole application: if two routes share a name, one silently replaces the other. Second, if you leave name out, Symfony generates one from the path and method, but explicit names are far easier to read in templates and logs, so always write them.

Methods and the 405 response

When methods is set, a request with another method does not match that route. If no other route matches either, Symfony answers 405 Method Not Allowed and lists the allowed methods in an Allow header. This is how you give the same path to two controllers, one for showing a form and one for processing it:

PHP
// real Symfony, read-only
#[Route('/contact', name: 'contact_form', methods: ['GET'])]
public function form(): Response { /* show the form */ }

#[Route('/contact', name: 'contact_send', methods: ['POST'])]
public function send(): Response { /* handle submission */ }

If you leave methods empty, the route matches every HTTP method. That is convenient for a quick demo and a common source of bugs in real apps, so set it on anything that changes data.

A router that reads attributes

The next stand-in defines its own Route attribute with the same arguments, collects routes from a controller class with ReflectionClass, and prints a route table. It also applies a class-level prefix, which the next section explains.

PHP Collecting routes from attributes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice how the class attribute's name: 'blog_' and path /blog were glued in front of each method's own values. Real Symfony does the same thing, with more care about edge cases.

Settings on the class

Repeating /blog on every method is tedious and error-prone. Put the shared part on the class:

PHP
// real Symfony, read-only
#[Route('/admin/posts', name: 'admin_post_')]
final class AdminPostController
{
    #[Route('', name: 'index', methods: ['GET'])]        // admin_post_index  /admin/posts
    public function index(): Response { /* ... */ }

    #[Route('/{id}/edit', name: 'edit', methods: ['GET', 'POST'])]  // admin_post_edit
    public function edit(int $id): Response { /* ... */ }
}

The class-level path is a prefix and the class-level name is a name prefix. Other class-level options, such as requirements, defaults, host, schemes, methods and condition, are combined with each method's own options. If the class itself has a __invoke() method, a single #[Route] on the class is enough.

Locale-aware paths and hosts

Two more options are worth knowing. host: 'admin.example.com' limits a route to one host, handy for admin panels or multi-tenant apps. Combine it with placeholders and requirements for tenant routing. And path can be an array that maps a locale to a path, so one controller serves /about in English and /a-propos in French:

PHP
// real Symfony, read-only
#[Route(['en' => '/about', 'fr' => '/a-propos'], name: 'about')]
public function about(): Response { /* ... */ }

Priority: who wins when two routes overlap

Routes are tried in the order they were loaded, and the first match wins. Files load in alphabetical order and methods in the order they appear in the class, which makes ordering fragile. The classic trap is /blog/{slug} appearing before /blog/new: the request for /blog/new matches the placeholder route, and slug becomes "new".

You have two clean fixes. Add a requirement to the placeholder so it cannot match new, or give the specific route a higher priority:

PHP
// real Symfony, read-only
#[Route('/blog/new', name: 'blog_new', priority: 10)]

Priority defaults to 0, and higher values are tried first. The next stand-in builds a tiny matcher with and without priority so you can watch the order change the answer.

PHP Priority decides who matches first (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first row is the interesting one: without priority, /blog/new is swallowed by the placeholder route.

Inspecting your routes

Never guess which route will win. Two console commands tell you:

Terminal
# real Symfony, read-only
php bin/console debug:router              # every route, in matching order
php bin/console debug:router blog_show    # details of one route
php bin/console router:match /blog/new    # which route would answer this URL

router:match is especially useful when a URL goes to the wrong controller; it prints the route that wins (add -v to see near misses).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does Symfony read #[Route] attributes from by default?

    The controllers resource in config/routes.yaml points the attribute loader at src/Controller/. Only classes found there are scanned.
  2. 2. What happens when a route has methods: ['GET'] and a POST request arrives for that path and nothing else matches?

    A path that exists for other methods produces 405 Method Not Allowed, with an Allow header listing the accepted methods.
  3. 3. A class has #[Route('/admin', name: 'admin_')] and a method has #[Route('/users', name: 'users')]. What are the resulting path and name?

    The class-level path is a prefix and the class-level name is a name prefix, so the method values are appended.
  4. 4. Routes /blog/{slug} and /blog/new overlap. What is the cleanest way to make /blog/new reach its own controller?

    The first match wins. A higher priority on the specific route (or a requirement that excludes it from the placeholder) fixes the order problem.

Summary

  • #[Route] above a controller method maps a URL to it; config/routes.yaml tells Symfony which directory to scan.
  • Always give routes a unique name, and set methods on anything that changes data.
  • requirements, defaults, host, schemes, condition and priority refine matching.
  • Put shared path, name and options on the controller class.
  • The first matching route wins, so use priority or requirements for overlapping paths, and check the result with debug:router and router:match.

Next up: Route Parameters and Requirements.