Back to results for “Map”
PHP › Symfony Framework Essentials

How does Symfony's routing system let you map URLs to controller actions, and what are the different ways routes can be defined?

Beginner

Answer

Symfony's routing system maps an incoming URL and HTTP method to a specific controller method responsible for handling it, and routes can be defined in several different ways depending on team preference, including using PHP attributes placed directly above a controller method, a separate YAML configuration file, or an XML configuration file, with attribute based routing being a particularly popular modern approach since it keeps the route definition visually close to the actual code that handles it.
#[Route('/products/{id}', name: 'product_show', methods: ['GET'])]
public function show(int $id): Response
{
    // handle the request
}
Real-world example A Symfony application defines each controller's route directly above its corresponding method using attributes, making it immediately obvious which URL pattern triggers which specific piece of code without needing to check a separate routing configuration file.

Common follow-ups: What is a route parameter, and how are route parameters passed into a controller method?;How does Symfony handle generating a URL from a named route rather than hardcoding it?