Entity or DTO: which data should a page receive from storage?

Build a Symfony list projection on MySQL 8.4/InnoDB: two reading strategies, a completed DTO for Twig, explicit initialization and checks of the read boundary.

The completed ribbon suggests a finished data projection ready for presentation.
The completed ribbon suggests a finished data projection ready for presentation.

The projection uses its own app.projection_connection to MySQL 8.4 through native PDO. Wire it explicitly into ReadConnection::$pdo, preserving the transaction exercise’s PDO service. Both strategies read synthetic data; the query counts below are test expectations rather than production measurements.

A list page needs a note title and the name of its category. The database stores more: relationships, internal fields and data used for editing. When a controller passes the entire storage object to a template, the boundary between retrieving data and displaying it becomes unclear. From the outside, the template only reads a property; inside, that access may mean another query.

The articles about Core, caching and presentation and the responsibilities of Admin, Frontend and API discussed consumer boundaries. Here I narrow the question to one list: exactly which data does it receive, and when does access to storage finish?

First, define the object's responsibility

An Entity has its own identity and can represent domain behaviour. In an application using an ORM, it also participates in persistence state management. A list DTO has a narrower job: carry values already prepared for a particular presentation. It should not know how to load a category or write an updated title.

This does not require copying every Entity into another class with the same fields. When an object needs an editing screen, working with the domain model can be natural. For an independent list, defining a dedicated read contract is more useful. An array can also provide that contract; here, a typed object makes its fields explicit and convenient to check.

Question Domain model object This list's DTO
What does it represent? A note with its identity and rules One completed row ready for display
Does it need storage relationships? Depends on the model's implementation No, only scalar values
Does it change data? May support permitted changes Contains no write operations
Who selects the fields? The domain model The contract of this particular list

Hidden reads have a concrete technical basis. Twig can resolve attribute access through an object method, and Doctrine describes lazy loading of associations. Combining such mechanisms can move queries into the moment when a template traverses objects. The actual behaviour must be checked against your own mapping and queries.

There is no ORM in this lab. The deliberate category lookup inside a loop will be written explicitly with PDO. It illustrates the cost of the chosen retrieval strategy but does not reproduce Doctrine's identity map, cache or every loading strategy. Its counters cannot be applied to an arbitrary ORM application.

The next step in the shared project

Continue the same Symfony project, article_demo, created from the official skeleton in the earlier articles. Run commands from its root. Add the required dependencies and files while preserving earlier routes, services and data. PHP 8.4+, Symfony 8.1 and Composer 2 remain the example requirements.

php --version
composer --version
composer require 'symfony/twig-bundle:8.1.*' 'ext-pdo:*' 'ext-pdo_mysql:*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/ReadModel src/Infrastructure src/Controller src/Command templates/projection_notes tests/ReadModel

After a real installation, retain composer.lock, symfony.lock and the package versions. The Composer lock file records the selected dependencies; the 8.1.* constraint alone does not identify an exact package set. Test dependencies may require additional PHP extensions.

Start with the contract. Create src/ReadModel/NoteRow.php:

<?php

declare(strict_types=1);

namespace App\ReadModel;

final readonly class NoteRow
{
    public function __construct(public int $id, public string $title, public string $categoryTitle)
    {
    }
}

Every field is complete before it reaches Twig. The scalar categoryTitle is not a reference to a category object. The DTO has no loader, connection or method that silently fetches more data. The identifier in this exercise is local: it helps order rows and verify the result, but it is not declared to be a future public Content ID.

Create src/Infrastructure/FixtureDatabase.php:

<?php

declare(strict_types=1);

namespace App\Infrastructure;

use PDO;

final class FixtureDatabase
{
    public static function connect(): PDO
    {
        return self::runtimeConnection(
            self::environment('DEMO_PROJECTION_DB_DSN'),
            self::environment('DEMO_PROJECTION_DB_USER'),
            self::environment('DEMO_PROJECTION_DB_PASSWORD'),
        );
    }

    public static function runtimeConnection(string $dsn, string $user, string $password): PDO
    {
        if (!str_starts_with($dsn, 'mysql:') || $user === '') {
            throw new \InvalidArgumentException('A configured MySQL runtime DSN and user are required.');
        }

        return new PDO($dsn.';charset=utf8mb4', $user, $password, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_STRINGIFY_FETCHES => false,
            \Pdo\Mysql::ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_0900_bin',
        ]);
    }

    public static function initializeSchema(PDO $migrator): void
    {
        if ($migrator->inTransaction()) {
            throw new \LogicException('Initialize the schema outside a transaction.');
        }

        // Serialize explicit initializers, not HTTP readers. No DDL belongs in the seed transaction.
        $database = (string) $migrator->query('SELECT DATABASE()')->fetchColumn();
        if ($database === '') {
            throw new \LogicException('Select a dedicated projection database first.');
        }
        $lockName = 'projection:'.substr(hash('sha256', $database), 0, 48);
        $lock = $migrator->prepare('SELECT GET_LOCK(?, 10)');
        $lock->execute([$lockName]);
        if ((int) $lock->fetchColumn() !== 1) {
            throw new \RuntimeException('Cannot acquire the projection initializer lock.');
        }

        try {
            $migrator->exec(<<<'SQL'
                CREATE TABLE IF NOT EXISTS projection_seed (
                    id TINYINT NOT NULL PRIMARY KEY,
                    CONSTRAINT projection_seed_singleton CHECK (id = 1)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin
                SQL);
            $migrator->exec(<<<'SQL'
                CREATE TABLE IF NOT EXISTS categories (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    title LONGTEXT NOT NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin
                SQL);
            $migrator->exec(<<<'SQL'
                CREATE TABLE IF NOT EXISTS notes (
                    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    title LONGTEXT NOT NULL,
                    category_id BIGINT NOT NULL,
                    internal_note LONGTEXT NOT NULL,
                    CONSTRAINT projection_notes_category_fk FOREIGN KEY (category_id) REFERENCES categories(id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin
                SQL);

            if ($migrator->query('SELECT id FROM projection_seed WHERE id = 1')->fetchColumn() !== false) {
                return;
            }

            $migrator->beginTransaction();
            try {
                if ((int) $migrator->query('SELECT COUNT(*) FROM categories')->fetchColumn() !== 0
                    || (int) $migrator->query('SELECT COUNT(*) FROM notes')->fetchColumn() !== 0) {
                    throw new \LogicException('Refusing to seed an unmarked, non-empty projection schema.');
                }

                $migrator->exec("INSERT INTO categories (id, title) VALUES (10, 'Architecture'), (20, 'Storage')");
                $migrator->exec(<<<'SQL'
                    INSERT INTO notes (id, title, category_id, internal_note) VALUES
                        (3, 'Third note', 20, 'Fixture-only detail C'),
                        (1, '<em>First note</em>', 10, 'Fixture-only detail A'),
                        (2, 'Second note', 10, 'Fixture-only detail B')
                    SQL);
                $migrator->exec('INSERT INTO projection_seed (id) VALUES (1)');
                $migrator->commit();
            } catch (\Throwable $failure) {
                if ($migrator->inTransaction()) {
                    $migrator->rollBack();
                }
                throw $failure;
            }
        } finally {
            $release = $migrator->prepare('SELECT RELEASE_LOCK(?)');
            $release->execute([$lockName]);
        }
    }

    private static function environment(string $name): string
    {
        $value = $_SERVER[$name] ?? $_ENV[$name] ?? getenv($name);

        return is_string($value) ? $value : '';
    }
}

The initial fixture contains 3 notes and 2 categories. The notes are inserted in a different order from the one expected on the page. Tables use InnoDB and utf8mb4_0900_bin; titles and internal text use LONGTEXT. NOT NULL and a foreign key enforce the required category, while a CHECK constrains the seed marker value. The internal field deliberately makes the table structure broader than the data in a displayed row.

PDO MySQL opens a configured schema rather than creating a fixture on every connection. For HTTP, first provision a dedicated teaching schema on MySQL 8.4 and separate runtime and migrator accounts. Set DEMO_PROJECTION_DB_DSN, DEMO_PROJECTION_DB_USER and DEMO_PROJECTION_DB_PASSWORD for runtime; the DSN must start with mysql: and select that schema. Runtime has DML privileges but no CREATE, ALTER or DROP. The separate app.projection_migrator service connects to the same schema with initialization privileges.

Define exactly what the counter measures

Create src/ReadModel/ReadConnection.php:

<?php

declare(strict_types=1);

namespace App\ReadModel;

use PDO;

final class ReadConnection
{
    private int $executions = 0;

    public function __construct(private readonly PDO $pdo)
    {
    }

    /** @return list<array<string, mixed>> */
    public function rows(string $sql, array $parameters = []): array
    {
        $statement = $this->pdo->prepare($sql);
        ++$this->executions;
        $statement->execute($parameters);

        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    public function count(): int
    {
        return $this->executions;
    }

    public function resetCount(): void
    {
        $this->executions = 0;
    }
}

The counter increments immediately before execute, after successful statement preparation. It covers only calls through this reader. Schema creation, fixture insertion and direct PDO changes in the tests are excluded. This is a narrow teaching instrument, not a complete SQL profiler or a time measurement tool.

The category parameter will be passed through a prepared PDO statement with emulation disabled, and results will use PDO row arrays. All SQL text is defined by code. The reader name alone does not restrict privileges: the runtime account is separate from the migrator that creates the schema during explicit setup.

The same DTO, different reading strategies

Create src/ReadModel/NoteList.php:

<?php

declare(strict_types=1);

namespace App\ReadModel;

final readonly class NoteList
{
    public function __construct(private ReadConnection $connection)
    {
    }

    /** @return list<NoteRow> */
    public function projected(): array
    {
        $rows = $this->connection->rows(<<<'SQL'
            SELECT n.id, n.title, c.title AS category_title
            FROM notes AS n
            INNER JOIN categories AS c ON c.id = n.category_id
            ORDER BY n.id ASC
            SQL);

        return array_map(static fn (array $row): NoteRow => new NoteRow(
            (int) $row['id'],
            (string) $row['title'],
            (string) $row['category_title'],
        ), $rows);
    }

    /** @return list<NoteRow> */
    public function perRowBaseline(): array
    {
        $notes = $this->connection->rows(
            'SELECT id, title, category_id FROM notes ORDER BY id ASC',
        );
        $result = [];

        foreach ($notes as $note) {
            $categories = $this->connection->rows(
                'SELECT title FROM categories WHERE id = :id',
                ['id' => $note['category_id']],
            );
            if (count($categories) !== 1) {
                throw new \UnexpectedValueException('The note requires one category.');
            }

            $result[] = new NoteRow(
                (int) $note['id'],
                (string) $note['title'],
                (string) $categories[0]['title'],
            );
        }

        return $result;
    }
}

The perRowBaseline method first reads the notes, then looks up a category for every row. Even a repeated category causes another call: there is deliberately no local cache. The 1 + N pattern comes from the reading algorithm. Wrapping the result in a DTO does not remove it.

The projected method selects the fields needed by the list and the related category name together. Column names are mapped to the DTO contract in one place. The order is set by ORDER BY n.id ASC: do not rely on MySQL row order without explicit sorting. The unique local identifier completes that rule without unresolved ties.

Condition for this fixture Reads inside a loop JOIN projection
Complete list 4 calls 1 call
Empty notes table 1 call 1 call
Reading the projection again after a category change Not assessed by this row Another 1 call

The JOIN relies on a required category and a unique category table key. This is a many-to-one relationship that does not multiply notes. For a relationship with several tags, a simple join can create several rows per note; that calls for another contract, aggregation or a separate batched read. One SQL query is not a universal goal at any cost.

Call count is not speed either. JOIN cost, transferred data volume, indexes and execution plans need their own measurements. This exercise does not assess latency, memory consumption or scalability. For a large catalogue, fetching every row must be replaced with a coherent pagination strategy, rather than leaving this small example unchanged.

The template receives a completed list

Merge this fragment into the existing services block in config/services.yaml, preserving earlier registrations and imports. Keep the rest of the file.

services:
    _defaults: { autowire: true, autoconfigure: true }

    app.projection_connection:
        class: PDO
        factory: ['App\Infrastructure\FixtureDatabase', 'connect']

    app.projection_migrator:
        class: PDO
        factory: ['App\Infrastructure\FixtureDatabase', 'runtimeConnection']
        arguments:
            - '%env(DEMO_PROJECTION_DB_DSN)%'
            - '%env(DEMO_PROJECTION_DB_MIGRATOR_USER)%'
            - '%env(DEMO_PROJECTION_DB_MIGRATOR_PASSWORD)%'

    App\ReadModel\ReadConnection:
        autowire: true
        arguments:
            $pdo: '@app.projection_connection'

    App\Command\InitializeProjectionNotesCommand:
        autowire: true
        autoconfigure: true

    App\ReadModel\NoteList: ~
    App\Controller\ProjectionNotesController: ~

For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. Runtime has DML only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.

CREATE DATABASE demo_projection CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_projection_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_projection_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON demo_projection.* TO 'demo_projection_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_projection.* TO 'demo_projection_m'@'127.0.0.1';
DEMO_PROJECTION_DB_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_projection;charset=utf8mb4"
DEMO_PROJECTION_DB_USER=demo_projection_r
DEMO_PROJECTION_DB_PASSWORD="<runtime-password>"
read -r -p 'Migrator user: ' DEMO_PROJECTION_DB_MIGRATOR_USER
read -r -s -p 'Migrator password: ' DEMO_PROJECTION_DB_MIGRATOR_PASSWORD
printf '
'
export DEMO_PROJECTION_DB_MIGRATOR_USER DEMO_PROJECTION_DB_MIGRATOR_PASSWORD
php bin/console app:projection-notes:init
unset DEMO_PROJECTION_DB_MIGRATOR_USER DEMO_PROJECTION_DB_MIGRATOR_PASSWORD

The service factory opens one shared runtime PDO connection for these services without creating tables or inserting data. The DTO itself is not registered as a service. The controller remains the point that selects the page: create src/Controller/ProjectionNotesController.php:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\ReadModel\NoteList;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ProjectionNotesController extends AbstractController
{
    #[Route('/projection-notes', name: 'app_projection_notes', methods: ['GET'])]
    public function __invoke(NoteList $notes): Response
    {
        return $this->render('projection_notes/index.html.twig', [
            'notes' => $notes->projected(),
        ]);
    }
}

Symfony's render method passes the prepared context to the template. Create templates/projection_notes/index.html.twig:

{% autoescape 'html' %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Projection notes</title>
</head>
<body>
<main>
    <h1>Projection notes</h1>
    <ul>
    {% for note in notes %}
        <li data-note-id="{{ note.id }}">
            <h2>{{ note.title }}</h2>
            <p>{{ note.categoryTitle }}</p>
        </li>
    {% else %}
        <li>No notes yet.</li>
    {% endfor %}
    </ul>
</main>
</body>
</html>
{% endautoescape %}

The template reads completed scalars and handles an empty list. It has no repository, category query or call to an arbitrary domain model method. Text uses HTML escaping; the fixture string containing tags must remain visible text. A DTO does not remove the requirement for safe output.

A completed DTO is also a snapshot of values at the time of reading. If the category changes later, the old object does not rebuild itself. A new reader call obtains new values. This makes the boundary clear, but it does not by itself define cache policy or page refresh behaviour.

A projection has its own scope

All notes in the teaching database are permitted for display. There are no drafts, multiple sites or personal records, so the example does not implement real authorization. In a product, the permitted set of rows must be established before passing results to the template. Selecting a few columns does not prevent reading someone else's record when the filtering condition is already wrong. Visibility policy and the data contract answer different questions.

The DTO field name is part of the agreement too. The category name is needed specifically as a row label; it does not imply that the template may change the category. If the table is later renamed or its data comes from another source, the mapping can change inside the reader while preserving the field's meaning for displayed rows. If the meaning of the label itself changes, that is a contract change that should be explained to the consumer and reflected in tests.

Sorting by a local identifier was chosen to make this lab easy to reproduce. It does not assert that a higher ID means a more recent publication or a higher editorial priority. A working list may need another business order and a separate rule for resolving equal values. Pagination must then continue that same order, instead of accidentally repeating or skipping records between pages.

There is also no need to create another DTO copy for every screen width. If desktop and mobile presentations need the same values, they can share a contract while using different Twig compositions. A different data set is justified by a different consumer need, rather than the mere arrival of another template. This helps avoid spreading a small storage change across many almost identical read models.

Check the boundary between reading and rendering

Create tests/ReadModel/NoteListTest.php. It checks row fields and ordering, different counters, rendering without another read, an empty collection, independence from a new internal field and behaviour after a database change. An SQL error does not become an empty list.

<?php

declare(strict_types=1);

namespace App\Tests\ReadModel;

use App\Command\InitializeProjectionNotesCommand;
use App\Infrastructure\FixtureDatabase;
use App\Infrastructure\MysqlLab;
use App\ReadModel\NoteList;
use App\ReadModel\NoteRow;
use App\ReadModel\ReadConnection;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
use Twig\Environment;

final class NoteListTest extends KernelTestCase
{
    private MysqlLab $fixture;

    protected function setUp(): void
    {
        parent::setUp();
        $this->fixture = MysqlLab::create('projection_read_mode');
        FixtureDatabase::initializeSchema($this->fixture->migrator());
        $this->fixture->exposeEnvironment('DEMO_PROJECTION_DB');
    }

    protected function tearDown(): void
    {
        try {
            parent::tearDown();
        } finally {
            if (isset($this->fixture)) {
                $this->fixture->close();
            }
        }
    }

    public function testBothReadersReturnTheSameOrderedRowsWithDifferentCounts(): void
    {
        $connection = new ReadConnection(FixtureDatabase::connect());
        $notes = new NoteList($connection);
        $baseline = $notes->perRowBaseline();

        self::assertSame(4, $connection->count());
        $connection->resetCount();
        $projected = $notes->projected();

        self::assertSame(1, $connection->count());
        self::assertEquals($baseline, $projected);
        self::assertSame([1, 2, 3], array_map(static fn (NoteRow $row): int => $row->id, $projected));
        self::assertSame(['Architecture', 'Architecture', 'Storage'], array_map(
            static fn (NoteRow $row): string => $row->categoryTitle,
            $projected,
        ));
    }

    public function testRenderingTheRowsDoesNotReadAgainAndEscapesText(): void
    {
        self::bootKernel();
        $connection = static::getContainer()->get(ReadConnection::class);
        $rows = static::getContainer()->get(NoteList::class)->projected();
        self::assertSame(1, $connection->count());

        $html = static::getContainer()->get(Environment::class)->render(
            'projection_notes/index.html.twig', ['notes' => $rows],
        );

        self::assertSame(1, $connection->count());
        self::assertStringContainsString('&lt;em&gt;First note&lt;/em&gt;', $html);
        self::assertStringNotContainsString('<em>', $html);
        self::assertStringNotContainsString('Fixture-only detail', $html);
    }

    public function testAnEmptyCollectionStillNeedsOnlyOneRead(): void
    {
        $pdo = FixtureDatabase::connect();
        $pdo->exec('DELETE FROM notes');
        $connection = new ReadConnection($pdo);

        self::assertSame([], (new NoteList($connection))->projected());
        self::assertSame(1, $connection->count());
    }

    public function testAnotherStorageFieldDoesNotExpandTheDto(): void
    {
        $pdo = FixtureDatabase::connect();
        $this->fixture->migrator()->exec("ALTER TABLE notes ADD COLUMN future_detail LONGTEXT NOT NULL DEFAULT ('Internal')");
        $rows = (new NoteList(new ReadConnection($pdo)))->projected();

        self::assertSame(['id', 'title', 'categoryTitle'], array_keys(get_object_vars($rows[0])));
        self::assertSame('<em>First note</em>', $rows[0]->title);
    }

    public function testACompletedDtoDoesNotChangeWhenTheDatabaseChanges(): void
    {
        $pdo = FixtureDatabase::connect();
        $connection = new ReadConnection($pdo);
        $notes = new NoteList($connection);
        $before = $notes->projected();
        $pdo->exec("UPDATE categories SET title = 'Changed category' WHERE id = 10");
        $after = $notes->projected();

        self::assertSame('Architecture', $before[0]->categoryTitle);
        self::assertSame('Changed category', $after[0]->categoryTitle);
        self::assertSame(2, $connection->count());
    }

    public function testAQueryFailureDoesNotBecomeAnEmptyCollection(): void
    {
        $pdo = FixtureDatabase::connect();
        $this->fixture->migrator()->exec('DROP TABLE notes');
        $notes = new NoteList(new ReadConnection($pdo));

        $this->expectException(\PDOException::class);
        $notes->projected();
    }

    public function testInitializerCommandPreservesAuthoredRowsAndDoesNotReseedDeletedRows(): void
    {
        $pdo = FixtureDatabase::connect();
        $pdo->exec("UPDATE notes SET title = 'Authored' WHERE id = 1");
        $pdo->exec('DELETE FROM notes WHERE id = 3');
        $tester = new CommandTester(new InitializeProjectionNotesCommand($this->fixture->migrator()));

        self::assertSame(0, $tester->execute([]));
        $rows = (new NoteList(new ReadConnection($pdo)))->projected();
        self::assertCount(2, $rows);
        self::assertSame('Authored', $rows[0]->title);
    }

    public function testInitializerRefusesUnmarkedAuthoredDataWithoutChangingIt(): void
    {
        $pdo = FixtureDatabase::connect();
        $pdo->exec("UPDATE notes SET title = 'Authored' WHERE id = 1");
        $this->fixture->migrator()->exec('DELETE FROM projection_seed');
        $before = $pdo->query('SELECT * FROM notes ORDER BY id')->fetchAll();

        try {
            FixtureDatabase::initializeSchema($this->fixture->migrator());
            self::fail('An unmarked populated schema must not be reseeded.');
        } catch (\LogicException $failure) {
            self::assertStringContainsString('Refusing', $failure->getMessage());
        }
        self::assertFalse($this->fixture->migrator()->inTransaction());
        self::assertSame($before, $pdo->query('SELECT * FROM notes ORDER BY id')->fetchAll());
    }

    public function testInitializerRefusesAnActiveMigratorTransaction(): void
    {
        $migrator = $this->fixture->migrator();
        $migrator->beginTransaction();
        try {
            FixtureDatabase::initializeSchema($migrator);
            self::fail('Initialization must not implicitly commit caller work.');
        } catch (\LogicException) {
            self::assertTrue($migrator->inTransaction());
        } finally {
            $migrator->rollBack();
        }
    }

    public function testRuntimeConnectionCannotPerformDdl(): void
    {
        $pdo = FixtureDatabase::connect();
        $this->expectException(\PDOException::class);
        $pdo->exec('CREATE TABLE forbidden_runtime_ddl (id BIGINT PRIMARY KEY) ENGINE=InnoDB');
    }
}

Symfony's KernelTestCase provides access to the test container and the real Twig service. The shared App\Infrastructure\MysqlLab helper from the earlier exercise supplies an isolated temporary MySQL schema; setup explicitly calls the initializer through its migrator. Separate native PDO connections within a test see the same schema. Structural changes for checks use the migrator, not runtime. The render check uses the reader and its counter from one kernel: a counter on another connection would prove nothing about the template's data.

composer validate --strict --no-check-publish
composer check-platform-reqs
composer show --locked --format=json
sha256sum composer.lock symfony.lock
find src tests -name '*.php' -print0 | xargs -0 -n1 php -l
php bin/console lint:yaml config/services.yaml
php bin/console lint:twig templates/projection_notes
php bin/console lint:container --env=test
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/ReadModel/NoteListTest.php --testdox

This PHPUnit command runs exactly the complete file included in the article. Before interpreting its result, check the actual exit code and the absence of errors and skipped tests. If versions or configuration change, a fresh run is needed; the expectations in the table do not replace it.

Before viewing the page, configure runtime and migrator for a dedicated teaching schema and run php bin/console app:projection-notes:init. The command uses src/Command/InitializeProjectionNotesCommand.php and the separate migrator. DDL runs before the seed transaction: MySQL DDL can implicitly commit transactions. The initializer rejects an already active migrator transaction; this is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database. After initialization, start the local server:

APP_ENV=dev php -S 127.0.0.1:8000 -t public public/index.php

Open http://127.0.0.1:8000/projection-notes. With the initial fixture, check note ordering, category names and the literal display of tags in the first heading. GET only reads data: it performs no DDL or seeding. Repeating explicit initialization on a marked schema preserves authored changes and does not restore deleted notes; the initializer refuses to seed a populated schema without a marker. Stop the test server with Ctrl+C. Use synthetic data rather than real users' records.

When this boundary earns its place

A dedicated read model is useful when a list has stable needs, combines data from several tables or must remain independent of ORM details. It lets you change the retrieval strategy while preserving the shape of Twig's context. The cost is maintaining the explicit field mapping and its checks.

For a small internal page with a model that has already been loaded, another DTO may simplify nothing. Make the decision around the actual responsibility boundary. Know which values the template receives, whether reading finishes before render, what happens after data changes and what evidence supports the expected query behaviour. Those questions remain useful regardless of the chosen class name.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

File src/Command/InitializeProjectionNotesCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\Infrastructure\FixtureDatabase;
use PDO;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[AsCommand(name: 'app:projection-notes:init', description: 'Initialize and seed the synthetic projection-notes schema once.')]
final class InitializeProjectionNotesCommand extends Command
{
    public function __construct(
        #[Autowire(service: 'app.projection_migrator')]
        private readonly PDO $migrator,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        FixtureDatabase::initializeSchema($this->migrator);
        $output->writeln('Projection notes schema initialized.', OutputInterface::OUTPUT_RAW);

        return Command::SUCCESS;
    }
}

Check the current example against an owned disposable MySQL schema:

  1. API An API response is not an Entity: designing an article card
  2. Architecture N+1 on an article page: find extra queries before premature optimization
  3. Architecture Ordering and pagination in a cached list: why equal values need a tie-breaker

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article