Symfony controller: one route, one action, one response

A Symfony controller is a PHP class whose actions, each linked to a URL by the #[Route] attribute, receive the request and return a Response.

class MenuController extends AbstractController
{
    #[Route('/menu', name: 'app_menu')]
    public function index(): Response
    {
        return $this->render('menu/index.html.twig', [
            'plats' => ['Grumpy dwarf stew', 'Elven mushroom pie', 'Dragon mead'],
        ]);
    }
}

The router maps the URL to the action, then Symfony calls it with arguments already resolved: route parameters, services, or values taken from the request by attributes such as #[MapQueryParameter] or #[MapRequestHeader]. So the action doesn't always need the whole Request object. AbstractController brings the render(), redirectToRoute() and createNotFoundException() shortcuts; a class with no parent and an __invoke() method is a controller too. The beginner's trap: writing $this->render(…) without return. The action then returns null, and Symfony stops on an error reminding you that a controller must return a Response, and asking whether you forgot a return.

The exercises have you declare the tavern's /menu route and render the menu in a Twig template, with a loop over the dishes, then rewrite an API controller so it reads the X-Api-Version header with #[MapRequestHeader] instead of the Request object, a missing header still giving a 400 error.

4 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

ClassRouteTwigStructMethodHttpKernel