Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 62 ยท Routing and Controllers

Your First Page

Build your first Symfony page: write a controller class, map a URL with the #[Route] attribute, return a Response, use make:controller and run a router stand-in.

A Symfony page needs only two things: a route that says "this URL belongs to that code", and a controller that returns a Response. Both fit in one small PHP class. There is no registration step and no configuration file to edit, because Symfony finds your controllers on its own and reads the route from an attribute written right above the method.

In this lesson you will create a page the real way (with the make:controller command and by hand), learn what each line means, and then run a router stand-in that works the same way: it scans a class with reflection, reads #[Route] attributes and calls the matching method. If you want a refresher on attributes first, see the PHP lesson on attributes.

A controller is a plain class

A controller is any PHP callable that receives the request data it needs and returns a Response. In modern Symfony it is usually a method on a class stored in src/Controller/. Here is the smallest useful one (real Symfony, read-only):

PHP
<?php
// src/Controller/HelloController.php

namespace App\Controller;

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

final class HelloController
{
    #[Route('/hello', name: 'app_hello')]
    public function index(): Response
    {
        return new Response('<h1>Hello, Symfony!</h1>');
    }
}

Read it from the bottom up:

  • new Response(...) builds the HTTP response: body, status 200 and default headers. It is the only thing a controller must return.
  • #[Route('/hello', name: 'app_hello')] is a PHP attribute. The first argument is the path; name is a unique route name used later to generate URLs.
  • The class lives in App\Controller, in the file src/Controller/HelloController.php, as the PSR-4 rule from Project Structure requires.

Start the server, open /hello, and the page appears. There is no step in between: the file is enough.

How Symfony finds the route

The magic is a small piece of configuration that your project already has, config/routes.yaml:

YAML
controllers:
    resource:
        path: ../src/Controller/
        namespace: App\Controller
    type: attribute

It tells the Routing component: "scan every class in src/Controller/, and turn each #[Route] attribute into a route." In the prod environment the result is cached in var/cache/, so the scan costs nothing per request. In dev the cache refreshes whenever a file changes.

You can see every route of the application with the router debug command:

Terminal
php bin/console debug:router
php bin/console debug:router app_hello      # details of one route
php bin/console router:match /hello         # which route matches this URL?

debug:router prints a table of name, methods, scheme, host and path. It is the first tool to reach for when a URL returns a 404.

flowchart LR
    A["config/routes.yaml<br/>scan src/Controller"] --> B["Read #[Route] attributes"]
    B --> C["Route collection<br/>(cached in var/cache)"]
    D["Request /hello"] --> E["Router matches path"]
    C --> E
    E --> F["HelloController::index"]
    F --> G["Response"]

At build time Symfony turns attributes into a route collection; at request time the router matches the URL and calls the controller.

Generating a controller

You rarely type the boilerplate yourself. The MakerBundle (installed in webapp projects, in dev only) generates it:

Terminal
composer require --dev symfony/maker-bundle     # only if it is not installed
php bin/console make:controller HomeController

The command creates src/Controller/HomeController.php, and in a project with Twig it also creates templates/home/index.html.twig. A typical generated controller extends AbstractController and renders the template:

PHP
final class HomeController extends AbstractController
{
    #[Route('/home', name: 'app_home')]
    public function index(): Response
    {
        return $this->render('home/index.html.twig', [
            'controller_name' => 'HomeController',
        ]);
    }
}

AbstractController is a convenience base class that gives you helpers like render(), redirectToRoute() and json(). It is optional: the plain HelloController above works without it. You will compare both styles in Controllers in Depth, and learn Twig in the chapter after that.

The stand-in router

Now you will build the mechanism yourself. The stand-in below uses a Route attribute class that you define here (the real one lives in Symfony\Component\Routing\Attribute), a controller class, and a router that reads the attributes through reflection, exactly the technique Symfony's attribute loader is built on.

PHP A router that reads #[Route] 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.

Look at what the output shows. The helper() method has no attribute, so it never becomes a route: a public method is not a page until it has a route. And an unknown path returns a 404 response. In real Symfony a missing route raises a NotFoundHttpException, which the kernel's kernel.exception event turns into the 404 page, as you saw in From Request to Response.

Single-action controllers

When a controller has just one action, you can make the class itself invokable and put the attribute on the class or on __invoke:

PHP
final class AboutController
{
    #[Route('/about', name: 'app_about')]
    public function __invoke(): Response
    {
        return new Response('About us');
    }
}

Many teams prefer this style for larger apps: one class per page, with a clear name, and easier testing. Other teams group related pages in one class, like BlogController with index, show and edit. Both are fine; choose one style and use it consistently.

The second stand-in collects routes from both places: attributes on the class (for __invoke controllers) and attributes on methods. It then calls every controller and prints a route table with each response.

PHP Invokable controllers and a page index (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.

Common mistakes

  • Forgetting the import. #[Route] needs use Symfony\Component\Routing\Attribute\Route;. Without it PHP looks for App\Controller\Route, and Symfony never sees the attribute. Older tutorials show Symfony\Component\Routing\Annotation\Route; that namespace is the deprecated one.
  • Returning a string. A controller must return a Response (or something a kernel.view listener converts). return 'Hello'; raises an error that says exactly this.
  • Two routes with the same name. Names must be unique, otherwise one silently replaces the other.
  • A controller outside src/Controller/. The loader only scans the folder configured in routes.yaml.
  • Stale cache. If a route is missing in production after a deploy, clear the cache with php bin/console cache:clear --env=prod.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a controller return?

    The kernel needs a Response. Returning a plain string raises an error unless a listener converts it.
  2. 2. Which attribute class do you import for routes in current Symfony?

    The Attribute namespace is the current one. The Annotation namespace is the old, deprecated alias.
  3. 3. Which command shows every route of the application?

    debug:router prints a table of routes; router:match /path tells you which route handles a URL.
  4. 4. A public controller method has no #[Route] attribute. What happens when you open its URL?

    Only methods (or classes) with a route are pages. Other public methods are ordinary PHP methods.

Summary

  • A page is a route plus a controller that returns a Response.
  • #[Route('/path', name: 'app_name')] on a controller method creates the route; config/routes.yaml makes Symfony scan src/Controller/.
  • make:controller generates the class (and a Twig template when Twig is installed); debug:router and router:match help you inspect routes.
  • Controllers may be plain classes; AbstractController only adds convenient helpers.
  • Single-action controllers use __invoke, with the route on the class or the method.
  • The stand-in router shows the mechanism: read attributes with reflection, match the path, call the method.

Next up: Routing with Attributes.