Where the controller ends: one use case for creating a note in Symfony
One shared note-creation use case for HTTP and Console in article_demo, with a domain rule, MySQL 8.4/InnoDB, atomic note-and-event persistence and separate schema initialization.
GET /notes from the first step remains a catalogue returning 200 and creates no records. POST /notes adds creation, while GET /notes/{id} reads a stored record. At this stage Note has only a title; the form chapter extends this same file with states while preserving title validation.
A specific HTTP request is a natural starting point for a controller. Read the JSON, validate the title, save the note and return a response: a small task fits comfortably into one method. The boundary becomes visible when the same kind of note also needs to be created by a console command. If that requires repeating the rules or calling the controller from the terminal, the use case is too closely tied to its entry point.
The article on Admin, Frontend and API discussed the responsibilities of separate applications. Here, we will work at a smaller scale: one operation within Symfony. We will build an independent teaching example in which HTTP and Console call a shared use case for creating a note. The data is synthetic, storage is local, and all the required files are included below.
Two entry points, one contract
One field is enough for this example: title. Before creation, we remove the leading and trailing characters handled by the standard trim() function and reject an empty result. We save the valid note in MySQL 8.4/InnoDB together with one created event in a single transaction. We return the note's id and normalised title; HTTP and Console use the same use case.
This rule must apply regardless of the entry point. A JSON object whose title consists of spaces and a console argument containing the same spaces should lead to the same domain rejection. The HTTP status and the command's exit code will be different representations of that rejection.
| Responsibility | Where it belongs | What the next step receives |
|---|---|---|
| Read the HTTP request | NoteController |
A title string |
| Read the command argument | CreateNoteCommand |
A title string |
| Perform creation | CreateNote |
A title for the domain object, then a note to save |
| Normalise the title and reject an empty one | Note |
A valid note or EmptyNoteTitle |
| Write and read data | MysqlNoteStore |
An identifier or a retrieved record |
Symfony allows a controller to run the logic an application needs; the framework does not require this particular structure. The controller documentation describes its work with Request and Response. I am choosing this boundary so that one use case can be reused through two entry points.
A separate environment for a small task
The example targets Symfony 8.1, PHP 8.4 or later, Composer 2, the PDO MySQL extension and a MySQL 8.4 server with InnoDB. Symfony's version requirements are listed on the 8.1 branch page, and the driver is described in the PHP manual. Application delivery and file permissions were covered in the article on Composer and 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 require 'symfony/console:8.1.*' 'ext-pdo:*' 'ext-pdo_mysql:*'
composer require symfony/serializer-pack 'symfony/validator:8.1.*'
composer require --dev symfony/test-pack
composer check-platform-reqs
Composer checks PHP extension requirements, but it does not install extensions in place of the system package manager. This exercise needs PDO MySQL; first prepare PHP and access to MySQL 8.4. The PHP database labs in the shared article_demo use MySQL; the root Composer requirements no longer include ext-pdo_sqlite or ext-sqlite3, and the Composer platform check passes without them. This does not change package versions. The exact set of dependencies is recorded in composer.lock after installation; a subsequent composer install uses those versions, as the Composer documentation explains.
The rule belongs to the note
The EmptyNoteTitle exception names a specific rejection. Its meaning does not depend on JSON, a form or a terminal.
File src/Domain/EmptyNoteTitle.php:
<?php
declare(strict_types=1);
namespace App\Domain;
final class EmptyNoteTitle extends \DomainException
{
}
The Note object accepts a string, normalises it and checks the result. Once the object has been created, its valid title can be read, but cannot be changed through the public property.
File src/Domain/Note.php:
<?php
declare(strict_types=1);
namespace App\Domain;
final readonly class Note
{
public string $title;
public function __construct(string $title)
{
$title = trim($title);
if ($title === '') {
throw new EmptyNoteTitle('A note title must not be empty.');
}
$this->title = $title;
}
}
The location of this check has a practical consequence: both entry points create the same type of note and receive the same rule. The controller does not need to pass an “already validated” flag, and the console command does not need to know exactly how leading and trailing characters are removed.
The rule's scope is deliberately narrow. The default character set for trim() is described in the PHP manual; it is not full Unicode normalisation. A non-empty title does not imply a unique title, either. Two identical valid titles in this lab create two records. A repeated request is a new operation; idempotency is not implemented here.
The use case defines the sequence
CreateNote describes a short operation: create a valid note, save it and return the result. It accepts an ordinary string and needs no Request, Response or InputInterface.
File src/Application/CreateNote.php:
<?php
declare(strict_types=1);
namespace App\Application;
use App\Domain\Note;
use App\Infrastructure\MysqlNoteStore;
final readonly class CreateNote
{
public function __construct(private MysqlNoteStore $store)
{
}
/** @return array{id: int, title: string} */
public function __invoke(string $title): array
{
$note = new Note($title);
$id = $this->store->save($note);
return ['id' => $id, 'title' => $note->title];
}
}
The order matters. If the Note constructor rejects the title, save() is not called. If writing to storage fails, the use case does not return a successful creation result.
A small array with a documented shape is enough for the two result values. A separate DTO would become appropriate if the result developed more complex behaviour or its contract needed a stronger expression in the type system. Likewise, the concrete MysqlNoteStore is currently an explicit dependency: the example does not promise that any storage mechanism can be swapped in automatically. An interface makes sense when a useful replacement boundary emerges, rather than simply adding another directory to the project.
Persistence is visible through both entry points
We will use a MySQL 8.4 server and InnoDB tables for this teaching task. The console process can exit, and a later HTTP request can read its note, provided both processes connect to the same schema using the same DSN. Persistence does not depend on process memory or a directory containing a database file: MySQL has no file-based or :memory: counterpart for this example.
File src/Infrastructure/MysqlNoteStore.php:
<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\Note;
final class MysqlNoteStore
{
public function __construct(
#[\Symfony\Component\DependencyInjection\Attribute\Autowire(service: 'app.notes_connection')]
private \PDO $connection,
)
{
if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) !== 'mysql') {
throw new \InvalidArgumentException('The notes store requires the MySQL PDO driver.');
}
$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}
public function save(Note $note): int
{
if ($this->connection->inTransaction()) {
throw new \LogicException('Note creation must own its transaction.');
}
$this->connection->beginTransaction();
try {
$statement = $this->connection->prepare('INSERT INTO notes (title) VALUES (:title)');
$statement->execute(['title' => $note->title]);
$id = (int) $this->connection->lastInsertId();
$this->connection->prepare('INSERT INTO note_events (note_id, kind) VALUES (?, ?)')
->execute([$id, 'created']);
$this->connection->commit();
return $id;
} catch (\Throwable $failure) {
if ($this->connection->inTransaction()) {
$this->connection->rollBack();
}
throw $failure;
}
}
/** @return array{id: int, title: string}|null */
public function find(int $id): ?array
{
$statement = $this->connection->prepare('SELECT id, title FROM notes WHERE id = :id');
$statement->bindValue(':id', $id, \PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch();
return $row === false ? null : ['id' => (int) $row['id'], 'title' => (string) $row['title']];
}
}
File src/Infrastructure/NotesSchema.php:
<?php
declare(strict_types=1);
namespace App\Infrastructure;
final class NotesSchema
{
public function __construct(
#[\Symfony\Component\DependencyInjection\Attribute\Autowire(service: 'app.notes_migrator_connection')]
private \PDO $connection,
)
{
if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) !== 'mysql') {
throw new \InvalidArgumentException('The notes schema requires the MySQL PDO driver.');
}
$connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}
public function initialize(): void
{
if ($this->connection->inTransaction()) {
throw new \LogicException('Notes initialization must not run inside a transaction.');
}
// Explicit lab initialization, not a migration or schema-repair system.
// MySQL DDL implicitly commits; do not wrap these statements in a transaction.
$this->connection->exec('CREATE TABLE IF NOT EXISTS notes (
id BIGINT SIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title LONGTEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci');
$this->connection->exec("CREATE TABLE IF NOT EXISTS note_events (
note_id BIGINT SIGNED NOT NULL UNIQUE,
kind TEXT NOT NULL,
CONSTRAINT fk_note_events_note FOREIGN KEY (note_id) REFERENCES notes(id),
CONSTRAINT chk_note_events_created CHECK (CAST(kind AS BINARY) = _binary'created') ENFORCED
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci");
}
}
File src/Command/InitializeNotesCommand.php:
<?php
declare(strict_types=1);
namespace App\Command;
use App\Infrastructure\NotesSchema;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:notes:initialize', description: 'Explicitly initialize the MySQL notes schema using the migrator connection.')]
final class InitializeNotesCommand extends Command
{
public function __construct(private readonly NotesSchema $schema)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->schema->initialize();
$output->writeln('Notes schema initialized.');
return Command::SUCCESS;
}
}
For a new local MySQL schema, run the following SQL as a database administrator and replace both password placeholders with your own distinct values. The account host here matches TCP access through 127.0.0.1; use the appropriate restricted host for another deployment. Save the runtime configuration below only in untracked .env.local. Read the migrator password in a separate terminal process for initialization; the variables are removed after the command.
CREATE DATABASE articledemonotes CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE USER 'article_demo_notes_runtime'@'127.0.0.1' IDENTIFIED BY '<choose-runtime-password>';
CREATE USER 'article_demo_notes_migrator'@'127.0.0.1' IDENTIFIED BY '<choose-migrator-password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON articledemonotes.* TO 'article_demo_notes_runtime'@'127.0.0.1';
GRANT CREATE, REFERENCES ON articledemonotes.* TO 'article_demo_notes_migrator'@'127.0.0.1';
DEMO_NOTES_DSN="mysql:host=127.0.0.1;port=3306;dbname=articledemonotes;charset=utf8mb4"
DEMO_NOTES_USER=article_demo_notes_runtime
DEMO_NOTES_PASSWORD="<chosen-runtime-password>"
The title is passed to a native prepared SQL statement as a parameter, with PDO::ATTR_EMULATE_PREPARES disabled. It is not concatenated into the SQL text; the mechanism is described in the PDO::prepare() documentation. MysqlNoteStore owns the transaction for the note and event, rejects calls inside a caller-owned transaction and rolls back on failure if its transaction is still active. A failed event write must not leave a saved note without its event.
The named connection app.notes_connection reads its DSN, user and password from DEMO_NOTES_DSN, DEMO_NOTES_USER and DEMO_NOTES_PASSWORD. HTTP and ordinary Console commands use a DML-only account without permission to execute DDL. Constructing the store only configures PDO; it does not create tables. PDO's exception mode lets a storage failure interrupt the use case; that failure must not be turned into a message about an empty title.
Before creating the first note, run app:notes:initialize separately: the command uses NotesSchema and app.notes_migrator_connection. Supply DEMO_NOTES_MIGRATOR_USER and DEMO_NOTES_MIGRATOR_PASSWORD only to the initialization process, not to the shared HTTP environment. The schema contains notes with a signed BIGINT AUTO_INCREMENT identifier and a LONGTEXT title using utf8mb4; in note_events, a foreign key and unique note_id associate one event with a note, while a constraint permits only the literal created for kind. Using IF NOT EXISTS is explicit teaching setup, not a schema upgrade, migration or data-copy system: old SQLite data is not transferred automatically, and an existing incompatible schema is not repaired. DDL stays outside the save transaction because of MySQL's implicit commits.
The controller translates HTTP into a use case call
We will define a specific HTTP contract:
| Situation | Expected response |
|---|---|
| Symfony does not recognize the format as JSON | 415 |
The JSON is malformed or a string title is missing |
400 |
The title is empty after trim() |
422 |
| The note has been saved | 201, JSON with id and title, and a Location header |
GET /notes/{id} finds a record |
200 and its JSON |
| No record exists | 404 |
Symfony determines the supported formats: acceptFormat: 'json' accepts MIME types that the framework recognizes as JSON, including application/json with MIME parameters. An unknown or different format results in 415. A missing title or an incorrect field type results in 400; a title that is empty after trim() results in a domain rejection with 422.
The distinction between 400 and 422 is a decision made for this API. RFC 9110 describes the status semantics, but we define how errors map to our particular contract. For 201, we return a Location at which the saved record can be read.
We describe the HTTP input using a separate CreateNotePayload: it contains a required title string, not a domain note. NotNull helps reject a missing value; the check for a title that is empty after normalization remains in Note. Symfony maps JSON to this object through MapRequestPayload.
File src/Input/CreateNotePayload.php:
<?php
declare(strict_types=1);
namespace App\Input;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class CreateNotePayload
{
public function __construct(
#[Assert\NotNull]
public string $title,
) {
}
}
File src/Controller/NoteController.php:
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Application\CreateNote;
use App\Domain\EmptyNoteTitle;
use App\Infrastructure\MysqlNoteStore;
use App\Input\CreateNotePayload;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;
final class NoteController extends AbstractController
{
#[Route('/notes', name: 'app_note_create', methods: ['POST'], format: 'json')]
public function create(
#[MapRequestPayload(acceptFormat: 'json', validationFailedStatusCode: 400)]
CreateNotePayload $payload,
CreateNote $createNote,
): JsonResponse {
try {
$created = $createNote($payload->title);
} catch (EmptyNoteTitle $error) {
return new JsonResponse(['error' => $error->getMessage()], Response::HTTP_UNPROCESSABLE_ENTITY);
}
return new JsonResponse($created, Response::HTTP_CREATED, [
'Location' => $this->generateUrl('app_note_show', ['id' => $created['id']]),
]);
}
#[Route('/notes/{id}', name: 'app_note_show', requirements: ['id' => '[1-9][0-9]*'], methods: ['GET'])]
public function show(string $id, MysqlNoteStore $store): JsonResponse
{
$numericId = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$note = $numericId === false ? null : $store->find($numericId);
return $note === null
? new JsonResponse(['error' => 'Note not found.'], Response::HTTP_NOT_FOUND)
: new JsonResponse($note);
}
}
The controller receives typed input: Symfony parses the JSON and checks its structure before the method is called. The method passes the title to CreateNote and produces an HTTP response. The domain rule remains in Note, while the creation sequence stays in the shared use case.
The controller catches the specific EmptyNoteTitle exception. A storage exception or a programming error does not mean that the client supplied an invalid title. Catching every Throwable and returning 422 would erase that distinction.
Reading through GET serves a supporting purpose here: it lets us check the result of persistence. A direct call to MysqlNoteStore is sufficient for this simple lookup; a separate read use case would not add another decision.
Console calls the same use case
The command needs the title argument, the CreateNote dependency and a way to present the result. It does not construct an HTTP request or call the controller's method.
File src/Command/CreateNoteCommand.php:
<?php
declare(strict_types=1);
namespace App\Command;
use App\Application\CreateNote;
use App\Domain\EmptyNoteTitle;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:note:create', description: 'Create one synthetic teaching note.')]
final class CreateNoteCommand extends Command
{
public function __construct(private readonly CreateNote $createNote)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('title', InputArgument::REQUIRED, 'The title of the note.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
$created = ($this->createNote)((string) $input->getArgument('title'));
} catch (EmptyNoteTitle $error) {
$errorOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
$errorOutput->writeln($error->getMessage(), OutputInterface::OUTPUT_RAW);
return Command::INVALID;
}
$output->writeln(
json_encode($created, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
OutputInterface::OUTPUT_RAW,
);
return Command::SUCCESS;
}
}
For this example, success means exit code 0 and JSON on standard output. We report a domain rejection on the error stream with code 2. This is the command's contract; not every possible console application error should receive that code. The Symfony Console documentation explains command registration, arguments, dependencies and exit codes.
OUTPUT_RAW keeps the output as plain text. The note's title must not accidentally be interpreted as Console formatting markup. HTTP and CLI present the result differently without changing the rule for a valid title.
Connect the required services
Add these registrations under the existing services key in config/services.yaml. Preserve earlier services, imports and settings; the fragment below shows additions, rather than a replacement of the whole file.
services:
_defaults:
autowire: true
autoconfigure: true
App\Application\CreateNote: ~
app.notes_connection:
class: PDO
arguments:
$dsn: '%env(DEMO_NOTES_DSN)%'
$username: '%env(DEMO_NOTES_USER)%'
$password: '%env(DEMO_NOTES_PASSWORD)%'
$options:
!php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
!php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
!php/const PDO::ATTR_EMULATE_PREPARES: false
app.notes_migrator_connection:
class: PDO
arguments:
$dsn: '%env(DEMO_NOTES_DSN)%'
$username: '%env(DEMO_NOTES_MIGRATOR_USER)%'
$password: '%env(DEMO_NOTES_MIGRATOR_PASSWORD)%'
$options:
!php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
!php/const PDO::ATTR_EMULATE_PREPARES: false
App\Infrastructure\MysqlNoteStore: ~
App\Infrastructure\NotesSchema: ~
App\Command\InitializeNotesCommand: ~
App\Controller\NoteController: ~
App\Command\CreateNoteCommand: ~
After registering the services, initialize the schema in a separate Bash process; migrator variables must be removed before starting HTTP.
read -r -p 'Migrator user: ' DEMO_NOTES_MIGRATOR_USER
read -r -s -p 'Migrator password: ' DEMO_NOTES_MIGRATOR_PASSWORD
printf '\n'
export DEMO_NOTES_MIGRATOR_USER DEMO_NOTES_MIGRATOR_PASSWORD
php bin/console app:notes:initialize
unset DEMO_NOTES_MIGRATOR_USER DEMO_NOTES_MIGRATOR_PASSWORD
The container creates the use case, storage and two adapters. We do not register Note or its exception as services: the use case creates a particular note from a particular title. Autowiring supplies the typed dependencies, and the store receives the named PDO connection app.notes_connection configured in the persistence section. The separate initialization connection does not grant schema-changing privileges to the HTTP process. These container mechanisms are described in the official documentation.
Reproduce the behaviour through HTTP and CLI
After creating the files, configure the runtime MySQL connection and initialize the schema separately using the persistence section's instructions. Do not pass migrator credentials to the server. Then check the configuration and start the local server:
php bin/console lint:yaml config/services.yaml
php bin/console lint:container
php bin/console debug:router app_note_create
php bin/console debug:router app_note_show
APP_ENV=dev php -S 127.0.0.1:8000 -t public public/index.php
The last command starts the built-in PHP server. It occupies the terminal until stopped with Ctrl+C. Run the following commands in a second terminal, also from the article_demo directory.
Creation through HTTP:
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json; charset=utf-8' \
--data '{"title":" Нотатка через HTTP "}'
We expect 201, the trimmed title and the actual id. Take the path from Location and open it on the same local server. The read response should contain this record. Do not assume the identifier is 1 or that identifiers are consecutive: earlier runs may have created notes, and AUTO_INCREMENT gaps after rollback are normal, not lost business records. See the InnoDB documentation for details.
Creation through the console:
APP_ENV=dev php bin/console app:note:create ' Нотатка через Console '
Using the returned id, open http://127.0.0.1:8000/notes/{id} with the actual value substituted. This checks persistence between separate processes. HTTP and Console must use the same DSN and MySQL schema in our single article_demo; sharing an application directory alone is not enough.
Next, reproduce the different reasons for rejection:
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: text/plain' --data 'not json'
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' --data '{"title":'
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' --data '{"title":17}'
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' --data '{"title":" "}'
APP_ENV=dev php bin/console app:note:create ' '
printf 'exit code: %s\n' "$?"
The expected HTTP statuses, in this order, are 415, 400, 400 and 422. For the last command, we expect an empty-title message and exit code 2. Compare these expectations with the actual response from each run. The presence of code alone is not enough to conclude that the required path already works.
Test the boundary by changing the requirements
Imagine that the HTTP client needs a different field name or response shape. That change can be kept in the HTTP adapter: read the new field, pass the string to the same CreateNote, then build the agreed JSON. The console command should not acquire a new argument merely because a field in the web contract has been renamed.
A new requirement for the note itself is a different case. If the product restricts acceptable titles, the corresponding rule must also apply to console creation. We then change the domain check and its tests, and check how both adapters represent the new rejection. Adding this requirement only to JSON validation would allow it to be bypassed through the second entry point.
Changing storage has a different cost. CreateNote currently depends directly on MysqlNoteStore, so independence from HTTP does not make it independent of the persistence mechanism. When a second implementation becomes necessary, we can extract a storage contract and change the use case's dependency. That choice follows from a new need, rather than the number of classes in the current example.
Reading changes this way helps us assess the structure more precisely than the controller's length does. The question is whether a particular entry point can change while the meaning of the operation remains intact, and whether a new domain rule reaches all the entry points that need it.
The smallest test of the rule
The title rule can be checked without HTTP, the container or the database. Save the file tests/Unit/NoteTest.php:
<?php
declare(strict_types=1);
namespace App\Tests\Unit;
use App\Domain\EmptyNoteTitle;
use App\Domain\Note;
use PHPUnit\Framework\TestCase;
final class NoteTest extends TestCase
{
public function testTrimsTheTitle(): void
{
$note = new Note(" \tA small note\n");
self::assertSame('A small note', $note->title);
}
public function testRejectsAnEmptyTitle(): void
{
$this->expectException(EmptyNoteTitle::class);
new Note('');
}
public function testRejectsAWhitespaceOnlyTitle(): void
{
$this->expectException(EmptyNoteTitle::class);
new Note(" \t\n ");
}
}
Run this exact test, which is included above:
APP_ENV=test php bin/phpunit tests/Unit/NoteTest.php
It checks normalisation, an empty string and a string containing only the whitespace characters handled at the edges, and remains database-free. MySQL behaviour, HTTP statuses and console streams need separate checks; Symfony describes different levels of testing in its documentation. Run the store integration test with bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/Integration/MysqlNoteStoreTest.php. The shared guarded fixture uses a cached MySQL 8.4 image for a disposable server, while App\Infrastructure\MysqlLab creates an owned isolated schema and separate migrator and runtime accounts. Test setup explicitly creates tables through the migrator; persistence, reads and result assertions use native PDO runtime connections, including separate connections sharing the same schema. Checks confirm that runtime DDL is forbidden and that an event-write failure rolls back the note: the test trigger raises SIGNAL SQLSTATE '45000', as described in the MySQL documentation. The failure propagates to the caller after rollback of the store's own active transaction. This command checks the store, not every HTTP and Console contract. The test fixture does not replace the separate DEMO_NOTES_* configuration and schema initialization needed for the manual HTTP and Console runs above.
This is where the chosen boundary becomes useful: the rule can be tested separately, the persistence use case with storage, and each adapter through its external contract. If file import is added later, it can also call CreateNote, passing the title and handling the defined rejection. Adding a new entry point therefore does not require rewriting the meaning of the operation itself.