The first useful page after the Symfony skeleton: a catalogue of learning notes

Build a small catalogue of learning notes in a fresh Symfony application, with a clear path from URL to HTML. Define and check distinct behaviour for normal content, an empty collection and an unavailable source.

A conceptual illustration of a card catalogue: cream cards and one terracotta card in an open dark metal holder.

In the server series, we reached a Symfony application that accepts a request through a web server and runs its front controller. A 404 response from the empty skeleton was expected at that point: the route for the page had not yet been defined. I covered that boundary separately in the article on a private Symfony application on E-01.

Now the page needs to give someone a reason to open it. For this first step, I am choosing a catalogue of learning notes: a few short entries with a title and an explanation. It provides a convenient way to follow the entire path from a URL to useful HTML and decide what to show when there are no entries or they cannot be retrieved.

This is an independent learning example built with Symfony. Its data is synthetic, and the source of the notes operates in memory. That lets us control the scenarios without connecting a database, an external API or the platform's working packages.

Define the page's behaviour before writing code

Let us begin by agreeing on the result of a GET /notes request. In the normal state, the reader sees the heading “Навчальні нотатки” and three cards. Each card has a title and a short summary; the learning source determines the order of the entries.

An empty catalogue also needs a clear result. If there really are no entries, the page explains this and returns 200. The reader should not have to guess whether a blank area is intentional or a rendering error.

An unavailable source means something different. In this example, we choose 503 and the message “Каталог тимчасово недоступний” for temporary unavailability. The data may exist, but we cannot display it at the moment. The meaning of this status is described in HTTP Semantics, section 15.6.4.

On this page, the catalogue is the main content: without it, the request cannot fulfil its purpose. A 503 response is therefore appropriate for the whole request. If only a supplementary block is unavailable, such as recommendations below the main article, the page can remain available while the block shows its own unavailable state. Choose the HTTP status according to whether the reader’s main request can be fulfilled.

Situation Expected HTTP status What the reader sees
Notes are available 200 A heading and cards
The collection is empty 200 An explanation that there are no notes yet
The source is temporarily unavailable 503 A separate unavailability message
An unknown path is requested 404 No matching route
DELETE is sent to /notes 405 This request method is not supported

An empty collection answers the question “what is in the catalogue?” A read failure means we did not obtain an answer to that question. If both cases are turned into an empty array, the page will misrepresent the state of the data.

A small learning project

The example targets Symfony 8.1 and PHP 8.4 or later, in line with the requirements for this Symfony branch. Work in a separate official skeleton. Environment setup and file permissions were covered in the earlier article on Composer and delivering Symfony.

We continue one teaching Symfony project, article_demo, independent of the private platform. We create it once in the first article; later steps add capabilities to the same application. All paths below are relative to the article_demo root.

composer create-project 'symfony/skeleton:8.1.*' article_demo
cd article_demo
composer require 'symfony/twig-bundle:8.1.*'
composer require --dev symfony/test-pack

Save the exact installed versions in composer.lock. A subsequent installation with composer install will use this set of dependencies; the Composer documentation explains the role of the lock file.

A controllable source

We will call the learning source DemoNoteCatalogue. It returns a list of notes or reports controlled unavailability through CatalogueUnavailable.

In src/Catalogue/CatalogueUnavailable.php:

<?php

declare(strict_types=1);

namespace App\Catalogue;

final class CatalogueUnavailable extends \RuntimeException
{
}

In src/Catalogue/DemoNoteCatalogue.php:

<?php

declare(strict_types=1);

namespace App\Catalogue;

final readonly class DemoNoteCatalogue
{
    /**
     * All entries are synthetic teaching data.
     *
     * @param list<array{title: string, summary: string}> $items
     */
    public function __construct(
        private array $items = [
            [
                'title' => 'Маршрут і відповідь',
                'summary' => 'URL зіставляється з контролером, який повертає HTTP-відповідь.',
            ],
            [
                'title' => 'Дані й шаблон',
                'summary' => 'Каталог готує записи, а Twig відображає їх як HTML.',
            ],
            [
                'title' => 'Порожній стан і недоступність',
                'summary' => 'Порожній список лишається успішною відповіддю; збій має окремий статус.',
            ],
        ],
        private bool $available = true,
    ) {
    }

    /**
     * @return list<array{title: string, summary: string}>
     *
     * @throws CatalogueUnavailable
     */
    public function all(): array
    {
        if (!$this->available) {
            throw new CatalogueUnavailable('The teaching catalogue is unavailable.');
        }

        return $this->items;
    }
}

The constructor parameters let us change the conditions in tests: we can supply an empty list or make the source unavailable. This models the behaviour of a dependency. It does not measure the availability of a real store or make network requests.

A source like this helps keep the first task small. Here, we define how the page behaves for different responses. Adding persistence will be a separate change with its own questions: what determines the order, how entries are updated and what a read failure means.

The route and the response

The route connects a URL to a controller, and the controller returns an HTTP response. In Symfony, a route can be declared with an attribute next to a method, as explained in the first-page documentation. For the catalogue, we set the stable name app_notes and restrict the read method with methods: ['GET'].

The file src/Controller/NotesController.php:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\Catalogue\CatalogueUnavailable;
use App\Catalogue\DemoNoteCatalogue;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class NotesController extends AbstractController
{
    #[Route('/notes', name: 'app_notes', methods: ['GET'])]
    public function __invoke(DemoNoteCatalogue $catalogue): Response
    {
        try {
            $notes = $catalogue->all();
            $unavailable = false;
            $status = Response::HTTP_OK;
        } catch (CatalogueUnavailable) {
            $notes = [];
            $unavailable = true;
            $status = Response::HTTP_SERVICE_UNAVAILABLE;
        }

        return $this->render(
            'notes/index.html.twig',
            [
                'title' => 'Навчальні нотатки',
                'notes' => $notes,
                'unavailable' => $unavailable,
            ],
            new Response(status: $status),
        );
    }
}

The controller distinguishes a normal response from a specific, expected source failure. It does not try to hide every application error behind an empty catalogue. For example, a template error needs to be diagnosed as a template error, rather than telling the reader that there are no notes.

Two useful commands can check the route itself:

php bin/console debug:router app_notes
php bin/console router:match /notes --method=GET

The first shows the registered route; the second helps determine whether it matches a particular path. These tools and HTTP method restrictions are described in the routing documentation. Their output does not yet prove that the template displays the notes correctly: that requires a request to the page.

The template explains the state to the reader

We will keep the presentation in templates/notes/index.html.twig. The controller passes the data and an unavailability flag, and the template chooses the corresponding view.

{% autoescape 'html' %}
<!doctype html>
<html lang="uk">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ title }}</title>
</head>
<body>
<main>
    <h1>{{ title }}</h1>

    {% if unavailable %}
        <p role="alert" data-state="unavailable">Каталог тимчасово недоступний. Спробуйте пізніше.</p>
    {% else %}
        <section aria-label="Список навчальних нотаток">
            {% for note in notes %}
                <article class="note-card">
                    <h2>{{ note.title }}</h2>
                    <p>{{ note.summary }}</p>
                </article>
            {% else %}
                <p data-state="empty">Нотаток поки немає.</p>
            {% endfor %}
        </section>
    {% endif %}
</main>
</body>
</html>
{% endautoescape %}

The order of these checks matters: unavailability comes first, followed by the normal list or a message explaining that the collection is empty. Once a failure is known, an empty array must not turn it into a successful empty state.

The note's title and description enter the HTML as text. Normal Twig output in Symfony escapes special characters; these fields do not need raw, which disables that escaping. This applies to our HTML text context. It is not a universal security guarantee for arbitrary URLs, JavaScript or trusted editorial HTML. See the template documentation for details.

Checks need to inspect the content

A page with a 200 status can display the wrong template or lose all its cards. For the normal scenario, we therefore check the status, heading and number of entries together. The empty state needs its own message and no cards. A failure needs 503 and no “Нотаток поки немає” message.

Another separate scenario is a title containing special HTML characters. It must remain text in the card heading, without creating nested HTML elements. This checks a specific output location instead of drawing a conclusion from the absence of anything suspicious during one viewing.

In Symfony, these scenarios can be described with WebTestCase: the test client makes a request, and assertions evaluate the response and its HTML. To require exactly 200, use assertResponseStatusCodeSame(200); an assertion of success alone allows the whole 2xx range. Examples of this approach are provided in the testing documentation.

We set the empty and unavailable states by replacing the learning service in the test container. The page does not need public parameters such as ?fail=1: a visitor should not control the failure simulation.

Before running the scenarios, we check the template and then run the specific test:

php bin/console lint:twig templates/notes/index.html.twig
APP_ENV=test php bin/phpunit tests/Controller/NotesControllerTest.php
php -S 127.0.0.1:8000 -t public public/index.php

The last command starts the local PHP server. Open http://127.0.0.1:8000/notes in a local browser. Read the titles and descriptions, and look at long text and a narrow window. Functional HTML checks and visual inspection answer different questions. This example contains no JavaScript. Stop the local server with Ctrl+C.

A sufficient first step

The value of a small catalogue lies in its complete behaviour. One URL has defined content, the empty state has an explanation, and unavailability is not disguised as an absence of entries. We can already discuss this feature in terms of what the reader sees and check it through expected responses.

The example should grow when the next need arises: adding a note, changing how it is stored or using the same data in another presentation. The initial page provides a small, understandable foundation for those changes.

Files for reproducing the checks

The test below covers all the scenarios in our contract and separately checks escaping in both text fields. To let the test replace the source before the first request, add config/services_test.yaml. This configuration applies only in the test environment:

# Loaded only in the test environment. Keep this service replaceable before a request.
services:
    App\Catalogue\DemoNoteCatalogue:
        public: true

Save the following file as tests/Controller/NotesControllerTest.php. The data and interface text are identical in every language version of this example:

<?php

declare(strict_types=1);

namespace App\Tests\Controller;

use App\Catalogue\DemoNoteCatalogue;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

final class NotesControllerTest extends WebTestCase
{
    public function testNormalCatalogueReturnsThreeCards(): void
    {
        $client = static::createClient();
        $client->request('GET', '/notes');

        self::assertResponseStatusCodeSame(Response::HTTP_OK);
        self::assertRouteSame('app_notes');
        self::assertPageTitleSame('Навчальні нотатки');
        self::assertSelectorTextContains('h1', 'Навчальні нотатки');
        self::assertSelectorCount(3, '.note-card');
        self::assertSelectorTextContains('.note-card h2', 'Маршрут і відповідь');
        self::assertSelectorTextContains(
            '.note-card p',
            'URL зіставляється з контролером, який повертає HTTP-відповідь.',
        );
        self::assertSelectorNotExists('[data-state="empty"]');
        self::assertSelectorNotExists('[data-state="unavailable"]');
    }

    public function testEmptyCatalogueIsAUsefulSuccessfulPage(): void
    {
        $client = static::createClient();
        static::getContainer()->set(
            DemoNoteCatalogue::class,
            new DemoNoteCatalogue(items: []),
        );

        $client->request('GET', '/notes');

        self::assertResponseStatusCodeSame(Response::HTTP_OK);
        self::assertSelectorCount(0, '.note-card');
        self::assertSelectorTextContains('[data-state="empty"]', 'Нотаток поки немає.');
        self::assertSelectorNotExists('[data-state="unavailable"]');
    }

    public function testUnavailableCatalogueIsNotAnEmptySuccess(): void
    {
        $client = static::createClient();
        static::getContainer()->set(
            DemoNoteCatalogue::class,
            new DemoNoteCatalogue(available: false),
        );

        $client->request('GET', '/notes');

        self::assertResponseStatusCodeSame(Response::HTTP_SERVICE_UNAVAILABLE);
        self::assertSelectorTextContains(
            '[data-state="unavailable"]',
            'Каталог тимчасово недоступний. Спробуйте пізніше.',
        );
        self::assertSelectorCount(0, '.note-card');
        self::assertSelectorNotExists('[data-state="empty"]');
    }

    public function testCatalogueTextIsEscapedInBothFields(): void
    {
        $title = '<em>Текст, а не HTML</em>';
        $summary = '<img src="missing"> & навчальний приклад';
        $client = static::createClient();
        static::getContainer()->set(
            DemoNoteCatalogue::class,
            new DemoNoteCatalogue(items: [['title' => $title, 'summary' => $summary]]),
        );

        $client->request('GET', '/notes');

        self::assertResponseStatusCodeSame(Response::HTTP_OK);
        self::assertSelectorCount(1, '.note-card');
        self::assertSelectorTextContains('.note-card h2', $title);
        self::assertSelectorTextContains('.note-card p', $summary);
        self::assertSelectorNotExists('.note-card em, .note-card img');

        $html = $client->getResponse()->getContent();
        self::assertIsString($html);
        self::assertStringContainsString('&lt;em&gt;Текст, а не HTML&lt;/em&gt;', $html);
        self::assertStringContainsString('&lt;img src=&quot;missing&quot;&gt; &amp;', $html);
    }

    public function testUnknownAddressRemainsNotFound(): void
    {
        $client = static::createClient();
        $client->request('GET', '/this-page-does-not-exist');

        self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND);
    }

    public function testUnsupportedMethodIsNotAllowed(): void
    {
        $client = static::createClient();
        $client->request('DELETE', '/notes');

        self::assertResponseStatusCodeSame(Response::HTTP_METHOD_NOT_ALLOWED);
        self::assertStringContainsString(
            'GET',
            (string) $client->getResponse()->headers->get('Allow'),
        );
    }
}

The test describes the expected behaviour. We can conclude that the behaviour is implemented only after running this exact set of files in the prepared environment.

  1. Platform Engineering Private Symfony on E-01: the Nginx → FPM → application path
  2. Symfony Core Where the controller ends: one use case for creating a note in Symfony
  3. Symfony Core Errors, empty results and missing records: three application responses