Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 62 ยท Routing and Controllers

Controllers in Depth

Understand Symfony controllers - AbstractController helpers, how arguments are resolved, controllers as services, invokable controllers and keeping actions thin.

A controller is any PHP callable that receives a request's data and returns a Response. That is the entire contract. Symfony does not care whether the callable is a method, an invokable class or a closure, and it does not require a base class. Everything else in this lesson is convenience on top of that one rule: helper methods, argument resolving and dependency injection.

Good controllers are boring. They read a little input, call the services that hold the real logic, and choose a response. This lesson shows what Symfony hands you, how it decides which arguments to pass, why controllers are services, and how to keep them thin enough to stay readable as the application grows. The runnable stand-ins here reproduce the argument-resolution mechanism with reflection, which is how the real ArgumentResolver works at its core.

The smallest controller

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

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

final class PingController
{
    #[Route('/ping', name: 'ping')]
    public function __invoke(): Response
    {
        return new Response('pong');
    }
}

No base class, no helpers, one action. Putting a #[Route] on a class with __invoke() is the "one controller, one action" style, which many teams prefer because every class has exactly one job.

AbstractController and its helpers

Most controllers extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController. It adds a set of small helpers:

Helper What it does
render('post/show.html.twig', $vars) Renders a Twig template into a Response
renderView(...) Renders a template to a string
json($data, 201) Builds a JSON response
redirectToRoute('name', $params) Redirects to a named route
generateUrl('name', $params) Generates a URL
addFlash('success', 'Saved') Stores a one-time message in the session
createNotFoundException('...') Builds an exception that becomes a 404 page
createAccessDeniedException() Builds an exception that becomes a 403
denyAccessUnlessGranted('ROLE_ADMIN') Checks permissions or throws
getUser() The logged-in user or null
createForm(Type::class, $data) Builds a form
file($path, 'name.pdf') Sends a file download
PHP
// real Symfony, read-only
final class PostController extends AbstractController
{
    #[Route('/post/{id}', name: 'post_show', requirements: ['id' => '\d+'])]
    public function show(int $id, PostRepository $posts): Response
    {
        $post = $posts->find($id) ?? throw $this->createNotFoundException('No such post.');

        return $this->render('post/show.html.twig', ['post' => $post]);
    }
}

Notice throw $this->createNotFoundException(...): the helper only creates the exception, you must throw it. Forgetting throw is a common bug.

AbstractController reaches the services behind its helpers through a small, fixed service locator. That means helpers work out of the box, but you cannot fetch arbitrary services from $this->container. Everything else must come in as a normal injected dependency, which is the next topic.

How arguments are resolved

When the kernel calls your controller it inspects each parameter and asks a chain of argument value resolvers whether they can provide it. The built-in ones handle, among others:

  1. Request: any parameter typed Request receives the current request.
  2. Route placeholders: a parameter whose name equals a route attribute ( fills $id).
  3. Backed enums and entities: as you saw in Route Parameters and Requirements.
  4. Attributes: #[CurrentUser] User $user, #[MapQueryParameter] int $page = 1, #[MapRequestPayload] and similar.
  5. Services: in controllers registered with the controller.service_arguments tag (the default for src/Controller/), parameters typed with a service class or interface are autowired.
  6. Default values and nullable types: used when nothing else supplies the value.

If no resolver can fill a required parameter, Symfony throws an error that names the controller and the argument. Order does not matter: show(PostRepository $posts, int $id) works the same as the version above.

flowchart TB
    K["Kernel found controller<br/>PostController::show"] --> A["For each parameter"]
    A --> R1{"Typed Request?"}
    R1 -- yes --> V["Pass the Request"]
    R1 -- no --> R2{"Route attribute<br/>with this name?"}
    R2 -- yes --> V2["Pass converted value"]
    R2 -- no --> R3{"Service or<br/>attribute resolver?"}
    R3 -- yes --> V3["Pass the service / mapped value"]
    R3 -- no --> R4{"Default or<br/>nullable?"}
    R4 -- yes --> V4["Pass default / null"]
    R4 -- no --> E["Error: cannot resolve argument"]

Each controller parameter is offered to resolvers in turn; the first one that can supply a value wins, and a required parameter nobody can fill is an error.

Resolving arguments yourself

This stand-in implements the same idea with ReflectionMethod. It builds the controller from a mini container (so its constructor dependencies are injected too), then fills each action argument from the request, the route attributes, the services or a default.

PHP An argument resolver built on reflection (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 call shows all kinds of arguments arriving together: the Request, a route attribute converted to int, a service, a default and a nullable value. The second call fails with an error that points straight at the culprit, which is also how Symfony reports problems.

Controllers are services

Because controllers are created by the service container, their constructor can type-hint other services and the container injects them (see Services and the Service Container later in the tutorial). You can also type-hint services on a single action when only one method needs them. Prefer the action when the dependency is used by one method, and the constructor when it is shared by many.

PHP
// real Symfony, read-only
final class ReportController extends AbstractController
{
    public function __construct(private readonly ReportBuilder $builder) {}   // used by several actions

    #[Route('/report/{id}', name: 'report_show')]
    public function show(int $id, LoggerInterface $logger): Response           // used by this action only
    {
        $logger->info('Report requested', ['id' => $id]);
        return $this->json($this->builder->build($id));
    }
}

Controllers outside src/Controller/ need the #[AsController] attribute so Symfony treats them as controllers.

Keep controllers thin

A controller is the translation layer between HTTP and your application. Parsing a request and building a response belong there. Pricing rules, email sending and database queries do not. A useful test: could you reuse this logic from a console command? If yes, it does not belong in a controller.

PHP Thin controller, testable service (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 assertions test the pricing rule with no HTTP at all. In a real project that is a plain PHPUnit test, which runs in milliseconds. The controller, in turn, is so small there is little left to test beyond wiring.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the only thing a Symfony controller must do?

    Any callable that returns a Response works. AbstractController is optional convenience.
  2. 2. What does throw $this->createNotFoundException() need the throw for?

    createNotFoundException() returns a NotFoundHttpException object. You must throw it for Symfony to answer with a 404.
  3. 3. A controller action is declared show(PostRepository $posts, int $id). Does the argument order matter?

    Resolvers look at each parameter's type and name, so the order in the signature is free.
  4. 4. Which belongs in a controller?

    Controllers translate between HTTP and the application. Business rules live in services so console commands and tests can reuse them.

Summary

  • A controller is any callable returning a Response; AbstractController only adds helpers such as render, json, redirectToRoute and createNotFoundException.
  • Arguments are resolved by type and name: Request, route placeholders, enums and entities, attributes such as #[CurrentUser], autowired services, then defaults and null.
  • Controllers are services: use constructor injection for shared dependencies and action arguments for one-off ones.
  • Remember to throw the exceptions the helpers create.
  • Keep actions thin and move business rules into services you can test without HTTP.

Next up: The Request Object.