Learn Symfony · 2/12

Routing and Controllers: The Core Request Loop

7 min read

Welcome to the beating heart of Symfony! Before we write any code, let's understand the "Request-Response Loop."

The Problem: In the early days of PHP, building a web application meant creating a physical file for every single page (about.php, contact.php, process_form.php). If two pages needed the same logic, you had to copy-paste code. Security checks had to be manually added to the top of every single file. It was a chaotic, unmaintainable mess.

The Solution: Modern frameworks route all incoming traffic through a single entry point (usually a single index.php file under the hood). From there, the framework figures out what the user wants and hands the task to a specific, organized piece of code.

🍕 The Pizza Shop Scenario:
Imagine you are running a pizza shop (the server). You have customers coming in constantly.

  1. A customer walks to the counter and says, "I want a large pepperoni pizza" (The Request).
  2. The cashier checks the menu to see who makes it (Routing).
  3. The cashier hands the order ticket to the Chef, who reads the ticket and bakes the pizza (The Controller).
  4. The Chef hands the hot pizza in a box back to the customer (The Response).

Every single action in a Symfony application follows this exact pattern: Request ➡️ Routing ➡️ Controller ➡️ Response.


1. Controllers: The Brains of Your Application 🧠

Definition

A Controller is a PHP method (inside a class) that you write to take information from the HTTP request and construct an HTTP response.

The Problem it Solves

You need an isolated, testable place to put your business logic for a specific page or API endpoint. Controllers act as the glue between the incoming request and your application's logic (like fetching data from a database).

How it Works (Alphabets to Words)

In Symfony, creating a controller is as simple as creating a PHP class. By industry standard, we extend a base class called AbstractController, which gives us helper methods (superpowers) to make our lives easier.

Instead of creating files manually, we use Symfony's MakerBundle to scaffold it perfectly every time:

bash
php bin/console make:controller PizzaController

Here is what a minimalist Controller looks like:

php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class PizzaController extends AbstractController
{
    public function getMenu(): Response
    {
        // 1. Do some logic (e.g., fetch pizzas from database)
        $pizzas = ['Pepperoni', 'Margherita', 'Hawaiian'];

        // 2. Return a Response object
        return new Response('<html><body>Menu: Pepperoni, Margherita, Hawaiian</body></html>');
    }
}

The Golden Rule of Controllers:
A controller must always return a Symfony\Component\HttpFoundation\Response object. It cannot return a string, an array, or an integer. It must be a Response (or a subclass of it, like JsonResponse).

Fun Fact: If you forget to return a Response, Symfony will throw a massive error screen that practically yells at you. It is very strict, which saves you from silent bugs in production!


2. Routing: Mapping URLs to Actions via PHP Attributes 🗺️

Definition

Routing is the system that maps a specific URL path (like /api/pizzas) to a specific Controller method.

The Problem it Solves

When a user navigates to yourwebsite.com/api/pizzas, the server has no idea what code to execute. Routing provides a map so the server knows exactly which Controller method handles that specific URL.

How it Works

In the dark ages of Symfony, developers had to maintain massive, hundreds-of-lines-long YAML files. Finding the route for a controller was like finding a needle in a haystack while blindfolded.

Today (in Symfony 7+ and PHP 8+), we use PHP Attributes. You attach the route definition directly above the controller method using #[Route].

php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route; // <-- Don't forget to import this!

class PizzaController extends AbstractController
{
    #[Route('/api/pizzas', name: 'api_pizza_list', methods: ['GET'])]
    public function listPizzas(): JsonResponse
    {
        return new JsonResponse(['Pepperoni', 'Margherita']);
    }
}

Breaking Down the #[Route] Attribute:

  1. The Path ('/api/pizzas'): The URL the user visits.
  2. The Name (name: 'api_pizza_list'): An internal nickname for this route. Industry Standard: Always name your routes. We will see why in Subtopic 4.
  3. The Methods (methods: ['GET']): Restricts this URL so it only works if the user makes a GET request. If they try to POST to it, Symfony blocks them automatically.

Dynamic Routing (Wildcards)

What if you want to view a specific pizza, like /api/pizzas/5? You don't want to create 100 routes for 100 pizzas. We use wildcards wrapped in curly braces {}.

php
    #[Route('/api/pizzas/{id}', name: 'api_pizza_show', methods: ['GET'])]
    public function showPizza(int $id): JsonResponse
    {
        // Symfony automatically extracts the {id} from the URL 
        // and passes it as the $id variable!
        return new JsonResponse(['id' => $id, 'flavor' => 'Pepperoni']);
    }

3. Mastering the HttpFoundation: Request and Response Objects 📦

Definition

The HttpFoundation component is an Object-Oriented replacement for PHP's native global variables (like $_GET, $_POST, $_SERVER) and native functions (like header(), echo).

The Problem it Solves

Native PHP globals are insecure, hard to mock in testing, and messy. If you use $_POST['name'] directly, you risk undefined array key warnings and security flaws. If you ever use $_POST in a modern Symfony app, a tiny puppy cries, and a senior developer senses a disturbance in the Force.

The Request Object

To read data coming from the user (like query parameters, form data, or JSON payloads), you simply ask Symfony to inject the Request object into your controller method.

php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// ... inside your controller class

#[Route('/api/orders', name: 'api_order_create', methods: ['POST'])]
public function createOrder(Request $request): Response
{
    // ❌ BAD (The 2005 way): 
    // $crust = $_POST['crust'];

    // ✅ GOOD (The modern Symfony way):
    $crust = $request->request->get('crust', 'thin'); // 2nd param is default fallback
    
    // Reading the URL query string e.g., ?discount_code=HALFOFF
    $discount = $request->query->get('discount_code');

    // Reading Modern JSON payloads (Symfony 6.3+)
    $payload = $request->getPayload();
    $size = $payload->get('size');

    return new Response("Order received for a $size pizza with $crust crust.");
}

⚠️ 2026 Industry Warning: If you are using Symfony 7.4+, the generic $request->get('key') method is officially deprecated! You must be explicit about where you are getting the data from:

  • $request->query->get() for URL parameters (?key=value).
  • $request->request->get() for HTML Form POST data.
  • $request->getPayload()->get() for JSON POST data.

The Response Object

We already know we must return a Response. The HttpFoundation component gives us specialized responses for common scenarios:

  • new Response('Hello') - Plain HTML/Text.
  • new JsonResponse(['status' => 'ok']) - Automatically converts arrays to JSON and sets the correct headers.
  • $this->render('pizza/show.html.twig') - A helper from AbstractController that returns a Response containing rendered HTML (we will cover Twig later).

4. Generating URLs and Managing Redirects 🔀

Definition

URL Generation is the process of creating a full URL string dynamically based on a route's name.
Redirecting is forcing the client's browser to navigate to a different URL (HTTP 301/302).

The Problem it Solves

Hardcoding URLs (like writing <a href="/api/pizzas/5"> in your frontend or redirecting to header("Location: /api/pizzas")) is a developer's worst nightmare.

Imagine your boss says, "Hey, we are rebranding. Change /api/pizzas to /api/gourmet-pies." If you hardcoded the URL, you now have to find and replace thousands of lines of code. If you miss one, users get 404 errors.

By generating URLs using the route's Name (remember name: 'api_pizza_list'?), you can change the actual URL path anytime you want, and your entire application will update instantly.

Generating URLs

Because your controller extends AbstractController, you have access to the $this->generateUrl() helper.

php
#[Route('/api/generate-link', name: 'api_link_maker')]
public function makeLink(): JsonResponse
{
    // Generate a link to the list
    $listUrl = $this->generateUrl('api_pizza_list'); 
    // Output: "/api/pizzas"

    // Generate a link to a specific pizza requiring a wildcard {id}
    $showUrl = $this->generateUrl('api_pizza_show', ['id' => 99]); 
    // Output: "/api/pizzas/99"

    return new JsonResponse([
        'go_here' => $listUrl,
        'or_here' => $showUrl
    ]);
}

Managing Redirects

Sometimes, after a user submits a form (like creating a new pizza order), you don't want to just show a blank page. You want to bounce them back to the menu. You do this using $this->redirectToRoute().

php
#[Route('/api/orders/submit', name: 'api_order_submit', methods: ['POST'])]
public function submitOrder(): Response
{
    // ... Save order to database ...

    // Send the user to the "api_pizza_list" route (HTTP 302 Redirect)
    return $this->redirectToRoute('api_pizza_list');
    
    // Need to redirect to an external site?
    // return $this->redirect('https://wikipedia.org');
}

Notice how clean that is? The Controller finishes its job, constructs a RedirectResponse object under the hood, and sends the browser exactly where it needs to go.


📚 References & Extra Reading

Challenge

Challenge: Build a Gadget API Controller

Your task is to implement a Symfony controller that provides a basic JSON API for managing a list of gadgets. You will need to create three distinct API endpoints using PHP attributes for routing.

Requirements:

  1. List All Gadgets:

    • Create a method getGadgetList.
    • Map it to the URL path /api/gadgets.
    • The route must have the name api_gadget_list.
    • It must only accept GET requests.
    • This method should return a JsonResponse containing the entire static $GADGETS array.
  2. Get a Single Gadget:

    • Create a method getGadgetDetail.
    • Map it to a dynamic URL path /api/gadgets/{id} where {id} is an integer.
    • The route must have the name api_gadget_detail.
    • It must only accept GET requests.
    • If a gadget with the given id exists in the $GADGETS array, return a JsonResponse with that gadget's data.
    • If the id is not found, return an empty JsonResponse with a 404 Not Found status code.
  3. Create a New Gadget:

    • Create a method createGadget that accepts a Request object.
    • Map it to the URL path /api/gadgets.
    • The route must have the name api_gadget_create.
    • It must only accept POST requests.
    • This method should read the JSON payload from the request to get a new gadget's name and price.
    • Simulate saving by creating a new gadget array with a hardcoded id of 99 and the provided name and price.
    • Instead of returning the new gadget, the method must return a RedirectResponse that redirects to the api_gadget_detail route for the newly created gadget (i.e., for id 99).

Expected result

Your completed controller should correctly implement all three routes with the specified logic for handling requests and generating appropriate responses, including JSON data, 404 status codes, and redirects.

php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class GadgetApiController extends AbstractController
{
    private static $GADGETS = [
        1 => ['name' => 'Quantum Screwdriver', 'price' => 150.00],
        2 => ['name' => 'Chrono-Lock Watch', 'price' => 375.50],
        3 => ['name' => 'Anti-Gravity Boots', 'price' => 899.99],
    ];

    #[Route('/api/gadgets', name: 'api_gadget_list', methods: ['GET'])]
    public function getGadgetList(): JsonResponse
    {
        return $this->json(self::$GADGETS);
    }

    #[Route('/api/gadgets/{id}', name: 'api_gadget_detail', methods: ['GET'])]
    public function getGadgetDetail(int $id): JsonResponse
    {
        $gadget = self::$GADGETS[$id] ?? null;

        if (!$gadget) {
            return new JsonResponse([], Response::HTTP_NOT_FOUND);
        }

        return $this->json($gadget);
    }

    #[Route('/api/gadgets', name: 'api_gadget_create', methods: ['POST'])]
    public function createGadget(Request $request): Response
    {
        // In a real app, you would validate and persist this data.
        // $name = $request->getPayload()->get('name');
        // $price = $request->getPayload()->get('price');
        $newGadgetId = 99;

        // The Post-Redirect-Get (PRG) pattern is common after a successful POST.
        return $this->redirectToRoute('api_gadget_detail', ['id' => $newGadgetId]);
    }
}
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.