Objectives and prerequisites
By the end of this course, you will be able to follow an HTTP request from start to finish in a Symfony application, design a small persistent feature, secure it, test it and prepare it for production. The common thread is a small book catalogue: a list, a detail page, a creation form, an edit form, a deletion, a search and a protected area. Each chapter extends the same project instead of stacking isolated examples.
Real prerequisites: you can write PHP functions and classes, you understand an HTTP request and response, and you can read a simple SQL query. No prior Symfony knowledge is required. This is an intermediate course, however: it does not merely make an example work, it explains the mechanisms, common errors and trade-offs. The examples use PHP 8.4, Symfony 7.4, Doctrine ORM 3, Twig 3 and MariaDB 10.6 in production; the lab may use SQLite to move faster, provided you check dialect differences before going live.
Announced path: chapters 1 to 4 set up the project and rendering; chapters 5 to 9 build persistence, forms and the CRUD flow; chapters 10 to 12 cover security, tests and deployment. The exercises are progressive and are corrected with the chapter code. Do not skip them: they turn reading into skill. Expect about thirty-five minutes of reading and two to four hours of practice for the whole course.
Working convention: every command runs from the project root. Code blocks name the relevant file when they are not commands to type in a terminal. Expected results are described after each example. Commands that produce variable output, such as an auto-incremented identifier, are identified as such.
1. Preparing a reproducible project
A Symfony application is first a Composer project. Composer downloads dependencies, builds the autoloader and records the exact installed versions in composer.lock. That file must be versioned: without it, two machines may install different versions and behave differently. Before creating the project, check that PHP 8.4 or a compatible version is available, that the extension for your database is enabled and that Composer 2 is installed.
php -v
composer --version
php -m | grep -E "pdo|mbstring|intl|xml"
The expected result is a PHP version, a Composer version and the list of found extensions. If an extension is missing, install it before continuing: an extension error often appears later as a confusing message. On macOS or Linux, a containerised environment can isolate these dependencies; it is not mandatory to follow the course.
Create the project with the Symfony skeleton. The directory name does not matter to the framework, but avoid spaces and accented characters in the path. The version constraint pins the branch used by the course; stay on 7.4 to follow the examples.
composer create-project symfony/skeleton:"7.4.*" book-catalogue
cd book-catalogue
composer require symfony/webapp-pack
php bin/console about
The about command shows the environment, the Symfony version and the project path. If it fails, read the message before changing configuration: it usually points to a missing dependency or an incomplete .env file. The webapp-pack adds Twig, Doctrine, forms, validation, security and the profiler; it speeds up the start without hiding the components, because each one remains configurable.
Look at the structure. public/index.php is the only public entry point: the web server sends every request to this file, which starts the Symfony kernel. src/ contains your code, config/ the configuration, templates/ the Twig views, migrations/ the schema changes and var/ the generated files. var/ must not be versioned; public/ contains the files the browser can actually access. This separation limits the exposed surface and makes deployment predictable.
Open .env and locate APP_ENV, APP_DEBUG and DATABASE_URL. The .env file contains versioned defaults; .env.local contains your personal values and must never be committed. For the lab, SQLite is enough: it creates a local file and requires no server. In production, use MariaDB or PostgreSQL according to the infrastructure, then check the SQL dialect and column types.
# .env.local
APP_ENV=dev
APP_DEBUG=1
DATABASE_URL="sqlite:///%kernel.project_dir%/var/catalogue.db"
composer.lock pins exact dependency versions, while symfony.lock remembers the Flex recipes applied to the project. Version both: the first guarantees an identical installation, the second explains which configurations the bundles added. Development dependencies, such as the profiler or testing tools, are not installed with --no-dev in production. This difference explains why a page may work locally and fail after deployment: production code must never require a development service.
Start the local server and open the home page. The development server reloads code on each request and displays detailed errors. Do not confuse this convenience with production: in production, APP_DEBUG must be zero, detailed errors must not be exposed and the cache must be built in advance.
symfony serve -d
# or, without the Symfony CLI:
php -S 127.0.0.1:8000 -t public
If the home page appears, the foundation is ready. If you get a 500 error, read var/log/dev.log and the profiler page. The first cause is often a missing environment variable; the second, a stale cache. php bin/console cache:clear rebuilds the cache, but it does not fix a wrong configuration. Always read the original error before clearing the cache.
2. Understanding the request/response cycle
An HTTP request reaches the server with a method, a path, headers and sometimes a body. The web server forwards it to public/index.php. Symfony builds a Request object, starts the kernel, resolves a route, calls a controller and turns the returned value into a Response. The server then sends that response to the client. Understanding this chain tells you where to look when a page does not behave as expected.
The kernel goes through several steps. HttpKernel dispatches events: kernel.request to prepare the request, kernel.controller to act before the controller, kernel.response to modify the response and kernel.exception to handle an error. Listeners subscribe to these events. This is how security, sessions, the profiler or localisation plug in without every controller calling them explicitly.
A web application must remain stateless between requests. The session keeps a few pieces of information for one user, but services must not store request-specific data in persistent properties. A shared service may be reused for several users; putting the current book or user identity there creates leaks that are hard to reproduce. Pass data through arguments, the request or an explicit session. This discipline makes tests simpler and behaviour predictable behind a server that handles several requests concurrently.
A request is more than a URL. It carries a method, headers, cookies and sometimes a body. The Content-Type header describes the body format; Accept expresses the response format the client prefers; Authorization carries credentials when the application uses tokens. Symfony exposes these values through the Request object, but you should read only what you need and validate it. A header is user input: never trust it for a security decision without checking the signature or the session behind it.
A response has a status code, headers and a body. Status 200 means success, 201 a creation, 204 no content, 302 a redirect, 400 a bad request, 401 authentication required, 403 access denied, 404 a missing resource and 500 a server error. A controller must not return HTML for a validation error: it returns the form with a 422 or 200 depending on the application convention, plus a clear message. The HTTP status is part of the contract with browsers, APIs and monitoring tools.
The router maps a path and HTTP method to a controller. It can extract parameters, apply constraints and generate URLs. A badly defined route produces a 404 even if the controller exists. Conversely, a correct route can produce a 500 if the controller throws an exception. Distinguishing these two families prevents you from changing the wrong layer.
The profiler, available in development, shows the resolved route, elapsed time, SQL queries, events and variables. Use it as a timeline: start with the route, then the controller, then the database, then rendering. This method is more effective than changing code at random. In production, the profiler is disabled; logs and metrics take over.
Mental exercise: open the home page, then request a nonexistent URL. Compare the status codes and the pages shown. Find the route, controller and response time in the profiler. This observation prepares the next chapters: you will soon know where to add your own route and how to explain each step.
3. Routes and controllers
A controller is a PHP class whose method returns a response. In Symfony, the #[Route] attribute maps a method to a path. The route name is used to generate URLs in templates and to redirect without hard-coding paths. The HTTP method is declared explicitly: a read route accepts GET, a creation route accepts POST. This precision prevents a simple link from triggering a deletion.
// src/Controller/BookController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
final class BookController extends AbstractController
{
#[Route('/books', name: 'book_index', methods: ['GET'])]
public function index(): Response
{
return $this->render('book/index.html.twig', [
'books' => [],
]);
}
}
The /books path is public by default until a security rule protects it. The book_index name is unique. The book/index.html.twig template will be created in the next chapter. If you call this route before creating the template, Symfony shows a clear error naming the missing file: a good diagnostic exercise.
Route parameters sit between braces and are injected into the method. The declared type lets Symfony convert the value and return a 404 if conversion fails. For a numeric identifier, declare int $id. For a slug, declare string $slug and add a route requirement if needed. Do not trust the received value: check that the resource exists and that the user may see it.
#[Route('/books/{id}', name: 'book_show', requirements: ['id' => '\d+'], methods: ['GET'])]
public function show(int $id): Response
{
return $this->render('book/show.html.twig', ['id' => $id]);
}
The \d+ requirement restricts the parameter to digits. Without it, /books/abc enters the controller with a string and fails later. The requirement turns an invalid input into a 404 at the right place. It does not replace the existence check: a numeric identifier may match no book.
A creation method accepts POST and reads the request body. A deletion method accepts POST or DELETE, never GET. Browsers cannot always send DELETE; Symfony provides forms with a _method field and CSRF protection. We will return to this with forms. For now, remember that the HTTP method is part of the action semantics.
Routes can be grouped by prefix and shared requirements. An /admin prefix avoids repeating the path on every action and lets you apply one security rule to a whole area. Localised routes use a prefix per language, for example /fr, /en and /sw, with the same route name and a locale parameter. This organisation requires checking link generation in every language and planning a redirect when no language is specified. It improves SEO and user experience, but adds variants to test.
Responses can be HTML, JSON, a redirect or a file. $this->json($data) serialises data and sets the Content-Type header. $this->redirectToRoute('book_index') returns a 302 redirect. $this->createNotFoundException() produces a 404. Use these helpers rather than manually building Response objects for every case: they reduce missing headers and make the code easier to read.
Exercise: create a /books/{id}/summary route that returns JSON containing the identifier and a fictional title. Test a valid identifier, a non-numeric identifier and a POST request. Note the status codes. You should see 200, 404 and 405. This experiment fixes the difference between a missing route, an invalid parameter and a disallowed method.
Cache headers are part of the response. Public content may be cached by the browser or a proxy for an explicit duration; personalised content must not be stored in a shared cache. The Cache-Control, ETag and Last-Modified headers avoid recomputing an unchanged page. Use them after checking data sensitivity and expected freshness. A cache that is too long shows stale information; no cache at all overloads the server. The right strategy depends on the content, not on a universal recipe.
4. Twig and rendering
Twig separates presentation from logic. A template receives variables, displays values and generates links. By default, Twig escapes HTML variables: a title containing <script> is displayed as text, not executed. Do not disable escaping with |raw without a precise reason. If you must display HTML produced by an editor, pass it through a sanitiser and document the decision.
Template inheritance avoids repeating the common structure. A base template defines blocks; child pages replace the useful content. Includes handle reusable fragments, such as a book card. This organisation reduces duplication and makes global fixes easier. It also has a cost: too many inheritance levels make reading difficult. Prefer one base level and targeted includes.
Twig compiles templates into PHP classes and caches the result. In development, the cache is invalidated when a template changes; in production, it is built in advance. A modified template that remains invisible in production often means a cache that was not warmed or an incomplete deployment. Escaping depends on context: a value displayed in HTML, in an attribute, in a URL or in JavaScript does not follow the same rules. Twig chooses the context when it knows the output type; for JavaScript or complex attributes, use the provided functions rather than concatenating strings.
{# templates/base.html.twig #}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}Catalogue{% endblock %}</title>
</head>
<body>
<main>{% block body %}{% endblock %}</main>
</body>
</html>
A page template extends the base and fills the body block. Internal links use path() with the route name, never a hand-written path. If the route changes, links follow automatically. Absolute URLs use url(). For static files, use the asset function configured by the project to benefit from versioning and caching.
{# templates/book/index.html.twig #}
{% extends 'base.html.twig' %}
{% block title %}Books{% endblock %}
{% block body %}
<h1>Books</h1>
<ul>
{% for book in books %}
<li>
<a href="{{ path('book_show', {id: book.id}) }}">{{ book.title }}</a>
</li>
{% else %}
<li>No books yet.</li>
{% endfor %}
</ul>
{% endblock %}
The for ... else loop handles the empty case without a separate condition. The title is escaped automatically. The identifier is passed to the named route. This template contains no SQL query and no business rule: it receives a collection already prepared by the controller. This separation lets you test logic without a browser and change presentation without touching data.
Accessibility is part of rendering. A page must have a single h1, hierarchical headings, explicit links and images with meaningful alternative text. Forms must associate each field with a label. Colour alone must not carry information. These rules are not decorative: they determine whether some users can actually use the catalogue.
Exercise: create the list template with an empty state, then a detail template showing the title and a back link. Verify that a title containing HTML characters is displayed as text. Add alternative text to any cover image. If you use a Twig component, check that the generated HTML remains valid and accessible.
Static assets also deserve a strategy. Versioned file names let the browser cache a file for a long time while a new deployment changes the URL. Compression reduces transfer size, and critical CSS or deferred scripts improve perceived speed. Do not optimise before measuring: the profiler and the browser network panel show whether the bottleneck is the database, a template or a large asset. A fast server response followed by a slow page often points to an unoptimised image or a blocking script, not to Symfony.
5. Services and the dependency injection container
A service is an object that performs one precise job: send an email, calculate a price, query a data source. The Symfony container instantiates these objects and injects them where needed. Dependency injection prevents a class from building its collaborators itself. It makes dependencies visible in the constructor and simplifies testing: a service can be replaced by a double without changing the calling class.
With autowiring, Symfony infers dependencies from declared types. A constructor asking for EntityManagerInterface, LoggerInterface or an application service receives the configured implementation. Autowiring does not remove the need to understand the container: if two implementations exist, you must choose explicitly. Errors such as "Cannot autowire service" usually indicate an unregistered type, an interface without an alias or a scalar argument without a value.
// src/Service/BookStats.php
namespace App\Service;
use App\Repository\BookRepository;
final readonly class BookStats
{
public function __construct(private BookRepository $books)
{
}
public function publishedCount(): int
{
return $this->books->count(['published' => true]);
}
}
This class only depends on a repository. It can be injected into a controller or a command. The readonly keyword prevents replacing the dependency after construction; it is not mandatory, but it is useful for stateless services. Avoid services that accumulate data across requests: in a web server, one instance may be reused and leak information between users.
Service configuration lives in config/services.yaml. Parameters, such as a file path or a sender address, can be declared there and injected with %parameter_name%. Secrets, such as an SMTP password or an API key, must not be versioned: use .env.local or the Secrets component. A configuration parameter is not a secret; a secret is not a business constant.
Services can be public or private. A private service is not fetched directly from the container; it is injected into the classes that declare it. This restriction avoids depending on an internal identifier and makes refactoring easier. Tagged services let you collect several implementations, for example calculation rules or commands. Compiler passes transform the container during its construction. These mechanisms are powerful, but they should not replace an explicit constructor dependency: start simple, then add a tag when several implementations must be discovered automatically.
The dev, test and prod environments load different configurations. Files under config/packages/test/ can replace a database or a mail service for tests. Never put test configuration in the shared file if it could affect production. Environment variables are resolved at startup; a missing value produces a clear error, which is better than a dangerous default.
Exercise: extract the published-book count into a service, inject it into the controller and display the result in the template. Then add a configuration parameter for the number of items per page and inject it. Verify that the controller no longer builds its dependencies itself. This small refactoring is the model for all the following ones.
6. Doctrine: entities and schema
Doctrine ORM maps PHP objects to relational tables. An entity is a persistent class; its properties become columns; its associations become foreign keys or join tables. Attribute mapping keeps the correspondence readable in the class. An entity must not contain SQL queries or container dependencies: it represents state and the object's local rules.
// src/Entity/Book.php
namespace App\Entity;
use App\Repository\BookRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: BookRepository::class)]
class Book
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 150)]
private string $title = '';
#[ORM\Column(type: Types::TEXT)]
private string $summary = '';
#[ORM\Column]
private bool $published = false;
#[ORM\Column]
private \DateTimeImmutable $createdAt;
public function __construct()
{
$this->createdAt = new \DateTimeImmutable();
}
public function getId(): ?int { return $this->id; }
public function getTitle(): string { return $this->title; }
public function setTitle(string $title): self { $this->title = $title; return $this; }
public function isPublished(): bool { return $this->published; }
public function setPublished(bool $published): self { $this->published = $published; return $this; }
}
The identifier is nullable before insertion and becomes an integer after flush. The title is a string limited to 150 characters; the summary is long text. The creation date is initialised in the constructor. Setters return self to allow chaining, but this convenience must not hide invariants: an empty title must be rejected by validation, not only by the interface.
The schema evolves through migrations. A migration is a versioned file describing a database transformation. It is replayed in the same order in every environment. Do not edit a migration already applied in production: create a new one. Before running a migration, read the generated SQL and back up data if the operation is destructive.
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate --no-interaction
php bin/console doctrine:schema:validate
The diff command compares the mapping with the schema and generates a migration. migrate applies it. validate checks that mapping and database are in sync. If validate reports a difference, do not fix the database by hand: identify the missing migration or the unversioned mapping change. Silent differences are a frequent cause of bugs between development and production.
The repository is the entry point for queries. It extends ServiceEntityRepository and exposes methods named after business needs, such as findPublished(). Avoid scattering DQL in controllers: the controller orchestrates, the repository queries. A repository method should be named after the result, not the way it is obtained.
// src/Repository/BookRepository.php
namespace App\Repository;
use App\Entity\Book;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<Book> */
class BookRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Book::class);
}
/** @return list<Book> */
public function findPublished(): array
{
return $this->createQueryBuilder('b')
->andWhere('b.published = :published')
->setParameter('published', true)
->orderBy('b.createdAt', 'DESC')
->getQuery()
->getResult();
}
}
A book belongs to an author: this is a ManyToOne association, because several books may share the same author. The inverse association, OneToMany, lets you traverse an author's books. Cascade tells which operations propagate from the parent object to related objects; use it carefully, because a cascade deletion may erase data you did not consider. orphanRemoval deletes a child when it is no longer referenced. For a price or an ISBN, an immutable value object may protect invariants better than a free string. These modelling choices have more impact on maintenance than column names.
Doctrine lifecycle callbacks run code at defined moments, such as before persisting or updating an entity. They are convenient for timestamps or normalisation, but they must remain small and predictable: a callback that sends an email or calls an external service makes persistence slow and surprising. Prefer an explicit service for side effects. Embedded value objects can group several columns, such as a price and its currency, behind one immutable object. They improve type safety, but they add mapping complexity; use them when the concept has rules, not for every pair of fields.
Exercise: add author and isbn properties to the entity, generate the migration and inspect the SQL. Create a findByAuthor(string $author) method in the repository. Insert two books with different authors and verify the result. Before continuing, explain why isbn should be unique and how a uniqueness constraint appears in the migration.
7. Doctrine: queries, unit of work and transactions
The EntityManager tracks loaded objects and their changes. persist() registers a new object in the unit of work; flush() computes the changes and executes the SQL. A loaded object that is modified does not need to be persisted again: Doctrine detects the difference at flush. This detection explains why one flush may produce several queries and why it must be placed at the right moment.
$book = new Book();
$book->setTitle('Docker in production');
$book->setPublished(true);
$entityManager->persist($book);
$entityManager->flush();
$id = $book->getId(); // available after flush
flush is a boundary. Before it, objects may be in an inconsistent state; after it, the database has changed. Group operations that must succeed together in a transaction. If an exception occurs, Doctrine rolls back the transaction and the database returns to its previous state. A transaction does not protect against a business error: it protects against a partial write.
Read queries use DQL or the QueryBuilder. DQL manipulates entities and their associations, not tables. The QueryBuilder builds a query step by step and makes conditional filters easier. For very specific queries or reports, native SQL remains possible, but you must then handle mapping and dialect portability. Do not mix the three styles in one method without a reason.
$qb = $bookRepository->createQueryBuilder('b')
->andWhere('b.published = :published')
->setParameter('published', true);
if ($search !== '') {
$qb->andWhere('b.title LIKE :search')
->setParameter('search', '%' . $search . '%');
}
$books = $qb->orderBy('b.title', 'ASC')->getQuery()->getResult();
The N+1 problem appears when a loop loads a collection for each item. For example, displaying ten books and loading each author with a separate query produces eleven queries. The solution is to join the association in the initial query, use a fetch join or prepare the data in one dedicated query. The profiler shows the number of queries; it is the first diagnostic tool.
The hydration mode determines the result shape: full objects, arrays, scalar values. Loading complete entities just to display two columns costs memory and time. For a read-only report, a DQL projection or a native query may be more appropriate. Conversely, object hydration is useful when business rules and associations must be available. Doctrine also offers pessimistic and optimistic locks for concurrent modifications; the optimistic lock adds a version number and fails if two users modify the same record. Choose these mechanisms according to the risk of conflict, not by default.
Pagination avoids loading a whole table. The KnpPaginator component, common in Symfony projects, takes a query and a page number. Without a component, compute limit and offset from the page and page size, then add a count query. Always check boundaries: a negative page, a page beyond the last result or an excessive page size.
Count queries need the same filters as the result query. If the list excludes archived books but the count includes them, pagination shows pages that contain no visible item. Build both queries from a shared filter method, or use a paginator that derives the count from the same query. Check the last page and the empty result explicitly. A pagination that works with three rows often breaks with ten thousand; test the boundaries before production, not after a user reports a blank page.
Exercise: write a method returning published books whose title contains a term, sorted by date, with a limit. Add a second method that counts the results. Use the profiler to verify that the list does not trigger one query per book. Explain what would happen if the author were loaded inside the template loop.
8. Forms and validation
A Symfony form links an HTTP request to an object. It reads data, applies constraints, fills the object and exposes errors. The form must not contain the complete business rule: it validates shape and simple constraints; the business service checks rules that depend on several objects or external state. This separation avoids duplicating validation in the interface and the API.
// src/Form/BookType.php
namespace App\Form;
use App\Entity\Book;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
final class BookType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title', TextType::class, [
'constraints' => [new Assert\NotBlank(), new Assert\Length(max: 150)],
])
->add('summary', TextareaType::class, [
'constraints' => [new Assert\NotBlank()],
])
->add('published', CheckboxType::class, ['required' => false])
->add('save', SubmitType::class, ['label' => 'Save']);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => Book::class]);
}
}
In the controller, handleRequest() reads the request and triggers validation. isSubmitted() indicates that a submission occurred; isValid() indicates that constraints pass. If the form is valid, persist and flush, then redirect. If the form is invalid, render the view again with the form: errors and entered values are preserved.
#[Route('/books/new', name: 'book_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$book = new Book();
$form = $this->createForm(BookType::class, $book);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($book);
$entityManager->flush();
$this->addFlash('success', 'The book has been created.');
return $this->redirectToRoute('book_index');
}
return $this->render('book/new.html.twig', ['form' => $form]);
}
Rendering a form with form_start(), form_row() and form_end() keeps hidden fields, labels and errors consistent. Avoid writing input tags by hand: you would lose CSRF, validation attributes and naming conventions. For a custom layout, render individual fields and labels while keeping the form's hidden fields. Check the generated HTML with a keyboard and a screen reader; a form that looks correct can still be unusable without a mouse.
CSRF protection is enabled by default in Symfony forms. It adds a token linked to the session and verifies that a submission comes from the form. Do not disable this protection to "simplify" an API: an API uses another authentication mechanism, such as a token, and does not rely on the browser session. If you see "The CSRF token is invalid", check that the form is rendered with its hidden fields and that the session is available.
Not every form should write directly to an entity. A form DTO isolates exposed fields, limits modifiable properties and prevents a user from changing an unexpected field. Validation groups apply different rules depending on context: creation, edition, draft or publication. Form events adapt fields based on a value, for example showing an extra field when a checkbox is ticked. For a file, check the real MIME type, size and dimensions, re-encode the image and store it outside the public path or behind an access controller. The form makes work easier, but file security remains a server responsibility.
Constraints produce messages for the user. A message must explain what is expected, not expose a technical exception. Translate messages if the application is multilingual and test edge cases: empty string, spaces only, maximum length, special characters, duplicate ISBN. Browser validation improves comfort, but it never replaces server validation.
Exercise: add author and ISBN fields to the form with appropriate constraints. Render the form in a template with errors. Submit an empty title, a too-short ISBN and a duplicate. Verify that the object is not persisted on error and that entered values remain visible. Explain why the uniqueness constraint must be checked in the database, not only in the form.
9. Complete CRUD and user experience
A complete CRUD is not four copied methods. It is a coherent journey: list, view, create, edit, delete, with messages, redirects and understandable errors. Each action must check that the resource exists and that the user has permission. A deletion must be confirmed and protected by CSRF. An edit must show current values and reject invalid data.
The list combines search, sorting and pagination. Search happens in the database, not in the template. Sorting must be stable: add a second criterion, such as the identifier, so that two items with the same date do not change order between pages. Pagination must preserve filters in links. These details seem minor, but they determine whether the interface remains usable with a lot of data.
#[Route('/books/{id}/edit', name: 'book_edit', methods: ['GET', 'POST'])]
public function edit(Book $book, Request $request, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(BookType::class, $book);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
$this->addFlash('success', 'The book has been updated.');
return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
}
return $this->render('book/edit.html.twig', [
'book' => $book,
'form' => $form,
]);
}
The Book $book parameter triggers conversion and returns a 404 if the identifier does not exist. This conversion is called the implicit ParamConverter. It avoids a manual find(), but it does not check permissions: an authenticated user could edit another user's book. Add a voter or an explicit check before processing the form.
Deletion uses a dedicated form with a CSRF token and the POST method. A GET link that deletes is dangerous: browser prefetching or a bot can trigger the action. After deletion, redirect to the list with a message. If the resource has dependencies, decide explicitly whether deletion is forbidden, cascaded or replaced by archiving.
Not every deletion is physical. Archiving with a deletedAt field preserves history, allows restoration and meets a retention obligation. It requires filtering queries to exclude archived items and deciding who may see them. An optimistic lock protects two simultaneous edits: if the version changed between reading and saving, the application asks the user to reload the page instead of silently overwriting another person's work. Finally, make actions idempotent where possible: replaying a confirmation must not create a duplicate. These choices are documented in the model and in tests.
Flash messages are stored in the session and displayed once. They must not contain sensitive data. Redirects after an action prevent a page reload from replaying the submission. This pattern is called Post/Redirect/Get. It improves the experience and prevents duplicates, but it does not replace a database uniqueness constraint.
Exercise: complete the journey with the detail page, edition and deletion. Add a confirmation, a success message and a redirect. Protect deletion with CSRF. Test a nonexistent identifier and verify the 404. Add a title search and a five-item pagination. Verify that filters remain active after changing page.
10. Security: authentication and authorisation
Authentication verifies identity; authorisation verifies what that identity may do. They are two distinct mechanisms. An authenticated person is not necessarily allowed to edit a book. A person allowed to read the list is not necessarily allowed to delete. Access control must be checked on every sensitive action, on the server. Hiding a button in the interface protects nothing.
Symfony provides a configurable security system. A provider loads users, a firewall defines how they authenticate, and access_control protects paths. The user entity implements UserInterface and, if needed, PasswordAuthenticatedUserInterface. Passwords are hashed with PasswordHasherInterface; never store a plain-text password and never compare two hashes with ===.
# config/packages/security.yaml
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
logout:
path: app_logout
access_control:
- { path: ^/books, roles: PUBLIC_ACCESS }
- { path: ^/admin, roles: ROLE_ADMIN }
The configuration above is a starting point, not a complete model. In production, add brute-force protection, an appropriate session lifetime, Secure and HttpOnly cookies, and a password policy. Second-factor authentication is recommended for administration accounts. Security secrets, such as the signing key, must not be versioned.
Roles are hierarchical strings. A ROLE_ADMIN role may include ROLE_USER. Use #[IsGranted('ROLE_ADMIN')] on a controller or method, or $this->denyAccessUnlessGranted(). For a rule that depends on the object, write a voter: for example, only the author may edit their book. The voter receives the user, the object and the attribute, and returns an explicit decision.
Complete authentication is not limited to the login form. Plan password reset through a signed, time-limited link, logout, session identifier regeneration after login and protection against repeated attempts. Rate limiting reduces brute-force attacks without permanently blocking a legitimate user. Session cookies must be Secure over HTTPS, HttpOnly and, if the application does not need cross-site access, SameSite=Lax or Strict. Login error messages remain deliberately generic. These measures complement authorisation; they do not replace it.
#[Route('/books/{id}/delete', name: 'book_delete', methods: ['POST'])]
public function delete(Book $book, Request $request, EntityManagerInterface $entityManager): Response
{
$this->denyAccessUnlessGranted('BOOK_DELETE', $book);
if ($this->isCsrfTokenValid('delete' . $book->getId(), $request->request->get('_token'))) {
$entityManager->remove($book);
$entityManager->flush();
}
return $this->redirectToRoute('book_index');
}
The CSRF token is linked to the action and the object. Manual verification is necessary here because deletion does not use a complete Symfony form. The BOOK_DELETE voter must be registered and tested. If the token is invalid, delete nothing and return an explicit response. Silent failure on deletion is both a security and a user-experience defect.
Security headers complement access control. Content Security Policy limits which scripts may run, X-Content-Type-Options: nosniff prevents MIME confusion, and Referrer-Policy limits information sent to other sites. HSTS forces HTTPS after the first secure visit. Configure these headers at the application or web-server level, then test them with the browser developer tools. A header that breaks a legitimate script must be adjusted deliberately, not removed in a hurry. Security is a set of layers, and each layer must be understood.
Exercise: create a login page, a test user with a hashed password, and protect creation, edition and deletion. Allow public reading. Test anonymous access, authenticated access without the role and administrator access. Verify that a user cannot edit another user's book. Note the 302, 403 and 200 status codes you obtain.
11. Tests and quality
An automated test verifies observable behaviour. A unit test isolates a class and replaces its dependencies. A functional test starts the kernel and sends an HTTP request; it verifies the route, controller, database and rendering. Both levels are complementary. A fast unit test does not prove that a page works; a slow functional test does not locate an error precisely.
// tests/Functional/Controller/BookControllerTest.php
namespace App\Tests\Functional\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class BookControllerTest extends WebTestCase
{
public function testIndexIsPublic(): void
{
$client = static::createClient();
$client->request('GET', '/books');
self::assertResponseIsSuccessful();
self::assertSelectorTextContains('h1', 'Books');
}
}
The test client follows redirects, keeps cookies and can submit forms. assertResponseIsSuccessful() checks the 2xx family, not only 200. assertSelectorTextContains() checks visible rendering. To test a creation, submit the form with valid data, verify the redirect, then verify that the object exists in the database. To test a validation error, submit an empty title and verify that the page remains accessible with a message.
Fixtures prepare a known state. They must be deterministic: no random dates, no dependency on an external service. Foundry factories simplify object creation and let you override a field. The test database must be isolated from the development database. The ResetDatabase trait resets the database to a known state before each test; use it while being aware of the cost.
Static quality complements tests. PHPStan detects inconsistent types and impossible calls. Linters check Twig, YAML and the container. Tests do not prove the absence of bugs, but they make regressions visible. A slow or flaky suite eventually gets ignored: keep unit tests fast and reserve functional tests for critical paths.
The test pyramid places many fast unit tests, fewer functional tests and a few end-to-end tests. This distribution gives fast feedback without giving up critical journeys. Code coverage is an indicator, not a goal: an executed line is not a verified rule. A flaky test fails sometimes without a code change; fix or remove it, because it destroys trust in the suite. Continuous integration runs tests, static analysis and linters on every change. The same script must run locally so a developer can reproduce a failure before pushing.
Functional tests often share a database and a container. Isolate each test's data and avoid depending on execution order. A test that passes alone but fails in the suite reveals a hidden dependency, not a framework problem. Factories should produce minimal, explicit values; random values make failures harder to reproduce. When a test depends on an external service, replace it with a double or a local test server. A test must fail for a clear reason and state the expected result, the actual result and the prepared state.
A useful CI pipeline is short and deterministic. It installs locked dependencies, prepares the test database, runs static analysis, linters and tests, then builds assets. Fail fast: run the cheapest checks first, but never skip the functional tests that cover the main journey. Cache dependency downloads and build artefacts to keep feedback under a few minutes. Store logs and reports as artefacts so a failure can be diagnosed without rerunning everything. The pipeline must use the same PHP and database versions as production, or it tests a different application.
Exercise: add a functional test for a book detail page, a valid creation test and an invalid creation test. Add an anonymous access test for the creation page and verify the redirect to login. Run PHPStan and fix type errors. Explain why a test that only checks status 200 does not prove that the right book is displayed.
12. Deployment, cache and operations
Deployment makes the application available in an environment different from the lab. Differences concern environment variables, the database, the web server, permissions and cache. A reproducible deployment starts from a versioned artefact, installs locked dependencies, applies migrations, builds assets, clears and warms the cache, then verifies that the application responds.
composer install --no-dev --optimize-autoloader --classmap-authoritative
php bin/console cache:clear --env=prod
php bin/console cache:warmup --env=prod
php bin/console doctrine:migrations:migrate --no-interaction --env=prod
yarn install --frozen-lockfile
yarn build
php bin/console assets:install public --env=prod
In production, APP_ENV=prod and APP_DEBUG=0. Detailed errors must not be visible; they must be logged. The web server must point to public/, never to the project root. var/ and public/uploads/ must be writable if the application needs it. Permissions must be minimal: the server user does not need to modify code.
Migrations are applied after a backup. A destructive migration must be tested on a database copy and accompanied by a rollback plan. The production cache is compiled: after deployment, check routes, assets, database connection and logs. A simple /health endpoint can verify that the application responds and that the database is reachable; it must not expose a secret.
Monitoring watches errors, latency and availability. Logs must be structured and kept long enough to diagnose an incident. Backups must be tested through an actual restore; a backup that was never restored is not proof. Dependency updates are done in batches, with tests and a planned rollback.
A zero-downtime deployment prepares the new version next to the old one, applies compatible migrations, switches traffic and removes the old version. This method requires backward-compatible migrations: add a nullable column before making it required, for example. Rollback must be possible without losing data written by the new version. For a small application, a deployment with a short interruption remains acceptable if it is announced and the backup is verified. In every case, measure recovery time, test restoration and keep deployment logs.
A backup is only useful if it can be restored. Define what is backed up: database, uploaded files, configuration and secrets. Store copies outside the production server and encrypt them if they contain personal data. Test a restore on a separate environment and measure how long it takes. Keep several generations so a corrupted backup does not destroy the previous one. Document who can restore, which command to run and how to verify data integrity. These details matter more than the backup frequency alone.
Exercise: prepare a deployment checklist for the mini-catalogue. Include backup, environment variables, migrations, cache, assets, permissions, health check and rollback. Simulate a deployment on a local copy of the database. Explain what would happen if a migration failed after going live.
Exercise 1 — A route that responds
Create a /books/welcome route that returns simple HTML with a title and a paragraph. Add an optional name parameter and display it. Verify that the route responds with 200 and that the name is escaped. Then add a second route that returns JSON and compare the response headers.
Solution
The route must declare GET, a unique name and a parameter with a default value. The controller can use render() or json(). The received name must be displayed through Twig, so it is escaped. If the parameter is absent, the default applies. The JSON must contain a clear structure, for example {"message":"Welcome"}, and a Content-Type: application/json header.
Exercise 2 — List and detail with Twig
Create a hard-coded book list in the controller, then a template that displays each title with a link to a detail page. Add an empty state. On the detail page, display the title and a back link. Verify that a title containing <script> remains text.
Solution
The list must be passed as a template variable. The for ... else loop handles the empty case. The link uses path() with the route name and identifier. Twig's automatic escaping prevents the script from executing. The detail page must handle a missing identifier with a 404, not an empty page.
Exercise 3 — An injected service
Create a service that counts published books. Inject it into the controller and display the result. Add a configuration parameter for the number of items per page and inject it too. Verify that the controller no longer builds its dependencies.
Solution
The service is a class automatically registered under src/Service when autowiring is enabled. The controller receives it through its constructor. The parameter is declared in services.yaml and injected with %name%. If two services implement the same interface, an explicit alias is required. The "Cannot autowire" error is diagnosed by reading the requested type and the container configuration.
Exercise 4 — Entity, migration and repository
Create the Book entity with a title, a summary, a published flag and a creation date. Generate the migration, apply it and verify the schema. Add a findPublished() method to the repository and test it with two books.
Solution
The entity uses Doctrine attributes and a generated identifier. The migration must contain the expected columns and nullability constraints. The repository extends ServiceEntityRepository and uses the QueryBuilder. The test must verify that only published books are returned and that the order matches the stated criterion.
Exercise 5 — Form and validation
Create a book form with title and summary constraints. Display it, submit an empty title and verify that the object is not persisted. Then submit valid data and verify the redirect and flash message.
Solution
The form uses data_class and field constraints. The controller calls handleRequest(), then checks isSubmitted() and isValid(). On error, it renders the view with the form and errors. On success, it persists, flushes and redirects. CSRF protection is enabled by default; if it fails, check the session and the rendering of hidden fields.
Exercise 6 — Functional test and security
Write a test verifying that the list is public and that an anonymous user is redirected to login to create a book. Log in a test user and verify that creation works. Add an access-denied test for a user without the required role.
Solution
The test uses WebTestCase and createClient(). For the anonymous user, check the 302 code and the destination. For the logged-in user, use loginUser() or the login form. For access denied, check 403. Test data must be created in a known state and cleaned by the reset mechanism. A security test that only checks whether the button is displayed does not prove that the route is protected.
Capstone — the complete mini-catalogue
Return to the common thread and deliver a working mini-catalogue: paginated list, search, detail, creation, edition, confirmed deletion, login, roles and tests. The catalogue must show an empty state, handle validation errors and refuse unauthorised access. It must use a versioned migration, a repository named after business needs and a service for a business rule. Add a simple health page and a readable error log.
Assessment grid: the user journey works end to end; rules are checked on the server; errors are understandable; tests cover listing, creation, validation and security; deployment commands are documented; no secret is versioned. To go further, add a read-only JSON API, author filters and configurable pagination. Document the trade-offs: simplicity, performance, security and maintenance cost.
Common errors and diagnostic method
A 404 means the route was not found or the resource does not exist. Check the path, HTTP method, route name and parameter. A 500 means an exception was thrown: read the log and profiler page, then walk up the stack to the first line of your code. An autowiring error indicates an unconfigured service or interface. A Doctrine mapping error indicates an inconsistent column or association. A CSRF error indicates a missing token or a lost session.
Method: reproduce the problem with the smallest possible request; check the route, then the controller, then the database, then the template. Add a temporary log instead of guessing. Compare development and production environments: cache, variables, permissions and dependency versions. Never fix an error by disabling security or validation; fix the cause.
Review and self-assessment
You should now be able to explain the request cycle, create a route and controller, render a Twig template, inject a service, model an entity, generate a migration, write a repository query, build a validated form, protect an action and write a functional test. If any point remains unclear, return to the corresponding chapter and redo the exercise without looking at the solution.
Self-assessment: I can explain why a route returns 404 rather than 500; I can distinguish persistence from flush; I can recognise an N+1 problem; I can explain the difference between authentication and authorisation; I can prepare a deployment with backup and rollback. To progress towards an advanced level, study voters, kernel events, integration tests, asynchronous messaging and caching strategies.
Reference documentation
- Symfony 7.4 — official documentation, consulted on 23 October 2026.
- Symfony — Routing and Controllers, consulted on 23 October 2026.
- Symfony — Doctrine ORM and Doctrine ORM, consulted on 23 October 2026.
- Symfony — Forms and Validation, consulted on 23 October 2026.
- Symfony — Security, consulted on 23 October 2026.
- Twig 3 — official documentation, consulted on 23 October 2026.
- PHPUnit — official documentation, consulted on 23 October 2026.
- PHP 8.4 — official manual, consulted on 23 October 2026.