The persistence layer of a Symfony project: entities in maker format with attribute mapping, auto-increment integer ids, \DateTimeImmutable and native enums; relations and the collection traps they open; repositories as the single place where DQL, QueryBuilder and raw SQL are allowed; SELECT NEW projections into Read DTOs; who calls flush(); and migrations that are generated then read and corrected by hand. Use this skill whenever someone asks to create or change an entity, add a field or a column, store or persist something, link two things together, add a relation or a foreign key, write or fix a repository method, write a query, sort or filter a list from the database, count rows, make a query return less data, create or run a migration, rename a column without losing data, or asks "why is my query wrong", "why is this null", "why does saving not work", "the schema is out of sync", "I lost data after deploying".
Ships in Symfony Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Tier: core — an entity, a repository and a reviewed migration are not optional.
SELECT NEWprojections are the on-demand part: reach for one when a list hydrates more than it shows.
Entities, relations, repositories, and migrations that survive contact with real data.
Everything here follows from one decision: entities are dumb. They are the maker shape — private properties, getters and setters, mapping attributes, nothing else. That choice has consequences all the way up the stack, so it is worth stating the consequence before the rules.
vendor/ is the source of truth over anything written here. This skill was verified
against Doctrine ORM 3.6, DBAL 4.4, doctrine-bundle 3.3 and Symfony 8.1; several APIs
that older blog posts still show no longer exist.
#[ORM\Entity(repositoryClass: BookRepository::class)]
class Book
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(enumType: ReadingStatus::class)]
private ReadingStatus $status;
#[ORM\Column(type: Types::DATE_IMMUTABLE, nullable: true)]
private ?\DateTimeImmutable $lastReadAt = null;
// getId(), getStatus(), setStatus(), … generated by make:entity
}
Auto-increment integer identifiers. Rejected: UUIDv7, ULID, an internal id plus a public one. They solve problems this standard does not have (offline id generation, hiding row counts) and they cost index size, readability in logs, and a conversation in every review.
\DateTimeImmutable, never \DateTime. A mutable date handed to a caller can be
modified behind the entity's back, and the change is silently persisted at the next
flush — a bug with no visible cause. Use Types::DATE_IMMUTABLE or
Types::DATETIME_IMMUTABLE; the plain date/datetime types map to \DateTime.
Native enums with enumType: for closed value sets, so the property is genuinely typed
and PHPStan can reason about it.
The consequence, stated plainly: an entity with a setter for every property enforces
nothing by itself. The maker shape is kept because one rule with no exceptions is easy
to hold and because make:entity, Form, fixtures and EasyAdmin all rely on it; the price
is that the guarantee rests on every write going through a service. So do not write
publish(), rate() or archive() on an entity: a method that guards one path next to
a setter that guards none is decoration. Every business rule lives in a service — the
entity is a typed row, the service owns the behaviour, the repository owns the SQL.
The one exception: an admin surface that bypasses services. EasyAdmin writes to the
entity directly, so no service rule applies there. Treat it as a trusted surface, and
when a local rule must still hold in the admin, duplicate it as an #[Assert] constraint
on the entity property, reading the same constants the service and the Input DTO read
(Book::MAX_RATING). EasyAdmin validates the entity, so the constraint produces a form
error there; it stays inert on the HTTP edge, where the Input DTO is what gets validated
(symfony-yoandev-http). The same goes for #[UniqueEntity]: on the Input DTO for the API, on
the entity too only if the admin edits that field.
Mapping details, relation ownership, cascade and orphanRemoval:
references/entities-and-relations.md.
Bidirectional when the inverse side is genuinely used — when a template or a service
really does walk from the book to its ratings. Unidirectional otherwise; a mappedBy
that nobody reads is a collection Doctrine has to manage for nothing.
The price of bidirectional is one specific trap:
count($book->getRatings()) // loads every rating row into memory
$book->getRatings()->count() // same thing
{{ book.ratings|length }} // same thing, in a template, in a loop
PersistentCollection::count() initialises the collection unless the association is
mapped fetch: 'EXTRA_LAZY'. On a list of 50 books that is 50 extra queries and every
rating in the database hydrated as an object, to display a number.
Count in the repository instead — countByBook(Book $book): int doing
->select('COUNT(r.id)'). For a list, one grouped query returning counts per book, not
one query per row. The query-count test that proves it belongs to symfony-yoandev-performance.
fetch: 'EXTRA_LAZY' makes count() issue a SELECT COUNT(*) instead of hydrating, and
it is a legitimate fix on an existing codebase where the calls are everywhere. It is not
the default here, because it makes an expensive call look free and hides the query from
the person reading the template.
The only place in the application where DQL, QueryBuilder or raw SQL may appear. Not a
style preference: it is what makes deptrac able to enforce the layer contract, and what
makes a slow page findable by grepping one directory.
/**
* Not `final` on purpose: service unit tests double it.
*
* @extends ServiceEntityRepository<Review>
*/
class ReviewRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Review::class);
}
/** @return list<Review> */
public function findLatestPublishedForBook(Book $book, int $limit = 10): array
{
return $this->createQueryBuilder('r')
->andWhere('r.book = :book')
->andWhere('r.publishedAt IS NOT NULL')
->setParameter('book', $book)
->orderBy('r.publishedAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}
Four things in that snippet are rules:
ManagerRegistry is Doctrine\Persistence\ManagerRegistry, and
ServiceEntityRepository is Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository.
Getting these two imports wrong is the most common Doctrine autowiring failure.final. Everything else in this standard is — services,
controllers, DTOs, voters, handlers — but a service unit test needs to double its
repository, and PHPUnit cannot double a final class. The one deliberate exception.@extends ServiceEntityRepository<Review> and @return list<Review>. Without the
generic annotation find() returns object and PHPStan at level max complains at
every call site; without the return annotation getResult() is mixed.findLatestPublishedForBook reads at the call site; findByBookIdOrderedByDate makes
the caller reconstruct why, and lies as soon as the query changes.$this->_em no longer exists — it was removed with ORM 3. Use the protected
$this->getEntityManager().
A list page that hydrates entities pays for the identity map, change tracking, and every column of every row, then uses four fields. Project instead:
/** @return list<ShelfStatsRow> */
public function findShelfStats(): array
{
return $this->createQueryBuilder('b')
->select(sprintf(
'NEW %s(b.id, b.title, AVG(r.rating), COUNT(r.id), b.lastReadAt)',
ShelfStatsRow::class,
))
->leftJoin('b.reviews', 'r')
->groupBy('b.id')
->getQuery()
->getResult();
}
The DTO lives in src/Dto/Read/ and holds raw values in the shape the query dictates.
The service normalises Read → Output (rounding, ISO dates, null versus 0); that
normalisation is a business rule and is unit-testable without a database. If the
projection already matches the API contract, project straight into an Output DTO and skip
the layer.
Two verified behaviours that decide how the DTO is typed: a column mapped with
enumType: arrives in the constructor as the enum, not as a string; and aggregate
columns arrive with platform-dependent PHP types. Details and the full pattern:
references/repositories-and-queries.md.
The service, once per use case. The repository does persist() and remove() and
stops there.
$book = (new Book())->setTitle($input->title); // maker shape: no constructor arguments
$this->books->add($book); // repository: persist() only
$this->entityManager->flush(); // service: one flush, one use case
$this->notifier->notifyShelfOwner($book);
A repository that flushes takes the decision away from the only object that knows whether the unit of work is finished — and it makes "add three books then save" cost three transactions. A service that flushes twice in one method usually has two use cases in it.
$entityManager->wrapInTransaction(callable $func) when several flushes genuinely must
succeed or fail together (a batch import, a state change plus a ledger write). Not by
default: a single flush() is already atomic.
php bin/console make:migration # or doctrine:migrations:diff
# read the file, correct it, then:
php bin/console doctrine:migrations:migrate
The generated file is a draft, never a deliverable. The generator compares two
schemas. It does not know about the rows already in the table, so a renamed property
comes out as DROP COLUMN plus ADD COLUMN — which is correct SQL, passes CI, and
destroys the column's contents in production. The fix is one hand-edited line
(ALTER TABLE … RENAME COLUMN …), and nothing but a human reading the file will catch
it.
The same applies to a new NOT NULL column on a populated table, to a type change that
silently truncates, and to down(), which the generator writes as the mechanical inverse
whether or not that inverse is possible.
Never doctrine:schema:update in production. It answers "make the database match the
mapping", which is a different question from "how do I get from the schema that exists,
with its data, to the one I want". Correcting a generated migration, data migrations and
the platform traps: references/migrations.md.
| Symptom | Cause |
|---|---|
| Changes are not saved | Nobody called flush(), or the service flushed before mutating |
| A list page fires hundreds of queries | count($x->getItems()) in a loop, or a relation walked in a template |
Cannot autowire … ManagerRegistry | Imported Doctrine\ORM\… or the DBAL registry instead of Doctrine\Persistence\ManagerRegistry |
getId() is null after saving | Read before flush(); the identifier is assigned by the insert |
| A date changed on its own | \DateTime instead of \DateTimeImmutable, mutated by a caller |
nullable ignored on a ManyToOne | ManyToOne has no nullable argument — it belongs on #[ORM\JoinColumn] |
| Schema out of sync, no migration pending | Mapping edited without generating a migration. Run doctrine:schema:validate |
| Deleting a parent throws a FK error | Missing cascade: ['remove'] or orphanRemoval, or the owning side is the other one |
| A removed child comes back | orphanRemoval not set: removing from the collection only unsets the reference |
| Data lost after a deploy | A generated DROP/ADD shipped where a RENAME was needed |
php bin/console doctrine:schema:validate is the check that the mapping still matches the
database. It validates the mapping, the sync state, and — since ORM 3 — that PHP property
types match their Doctrine types. It belongs in CI, where a forgotten migration fails the
build instead of the deploy.
| File | When to read it |
|---|---|
references/entities-and-relations.md | Adding a field or a relation, choosing cascade / orphanRemoval / the owning side, mapping an enum or a date |
references/repositories-and-queries.md | Writing or fixing a repository method, projections, aggregates, pagination, PHPStan annotations |
references/migrations.md | Before running a generated migration, renaming or backfilling a column, deploying a schema change |
What SKILL.md sets; muted values are Claude Code's defaults
/symfony-yoandev-skills:symfony-yoandev-doctrinefrom Symfony Skills
npx claudepluginhub yoanbernabeu/symfony-yoandev-skills --plugin symfony-yoandev-skills16 skills in this plugin
/symfony-yoandev-architectureDecide where code goes in a Symfony project and wire it correctly: the Controller / Service / Repository / DTO / Entity contract, the three DTO namespaces (Input, Read, Output), service design and who calls flush(), business exceptions carrying their own HTTP status, direct calls instead of domain events, configuration split between env vars, app. parameters and class constants, and the dependency-injection attributes (#[Autowire], #[AutowireIterator], #[AutowireLocator], #[AsDecorator], #[AsTaggedItem], #[Target], #[When], #[Lazy]). Use this skill whenever someone asks where a piece of logic belongs, wants a new service or DTO, says a controller has grown too big, wants to extract or move a class that has outgrown its place, asks how to make something configurable or add a setting or an env var, asks why a service is not autowired or how to inject one of several implementations, wants a factory, strategy, decorator or object mapping, or asks "is this the right place for this?", "how should I structure this feature?", "where does the rating logic go?", "extract this", "why does my exception return a 500?". Also use it for the list of alternatives this standard deliberately rejected and why. For a feature described in plain language, or a bare "refactor this" with no target, `symfony-yoandev-standards` routes first./symfony-yoandev-asyncMove work out of the request with Messenger, send email asynchronously with Mailer and TemplatedEmail, and run recurring jobs with Scheduler — Doctrine transport, retry and failure policy, prioritised queues, idempotent handlers, and workers under supervisor or systemd. Use this skill whenever someone asks to send an email, do something in the background, queue a job, run something every night or every five minutes, replace a crontab, speed up a slow import or a slow signup, process a big CSV, notify someone after an action, set up Messenger or a message handler or a worker, configure retries, deal with a message stuck in the failure queue, or says "my emails never arrive", "the import times out", "this page is slow because it sends mail", or "how do I schedule this"./symfony-yoandev-consoleWrite Symfony console commands as thin translation layers over a service: one class per command family with method-level #[AsCommand] on Symfony 8.1, invokable commands with #[Argument] and #[Option] before that, SymfonyStyle output, dry run by default with --force on anything destructive, mandatory locking on long or scheduled commands, clean shutdown on SIGTERM, and a smoke test with runCommand or CommandTester. Use this skill whenever someone asks to add a command, write a script, make something runnable from the terminal, build an import or an export or a batch job, clean up or purge or delete old data, backfill a column, send a digest, "run this once", "I need a CLI for this", "make:command", says a command times out or eats all the memory or deleted more than it should, or asks how to test a command. For scheduling that command to run every night, and for Messenger workers, use symfony-yoandev-async instead./symfony-yoandev-deploymentShip a Symfony application to production as a Docker image running FrankenPHP: the build and release sequence and what each step is for, migrations run automatically at deploy, production php.ini and OPcache preloading, environment variables and secrets on the server, Messenger workers under systemd or supervisor, post-deployment checks and rollback. Use this skill whenever someone says deploy this, put it in production, ship it, set up the server, prepare a Dockerfile or a production image, write a deploy script, run migrations on the server, restart the workers, configure OPcache or preloading, set environment variables in production, roll back a release — and equally when they describe a symptom: it works locally but not on the server, the site broke after deploying, my CSS is missing in production, production is slow, the workers are running old code, I get a 500 with no error message, the new code is not being picked up. Also use it before a first deployment, when nobody knows how the app is deployed./symfony-yoandev-frontendBuild and debug the front end of a Symfony application with AssetMapper, Twig, Stimulus, Turbo and Symfony UX — no bundler, no Node build step. Use this skill whenever someone asks to make a page interactive, add a filter or a live search, add an autocomplete or a dropdown, add a JavaScript library, style a page or set up Tailwind, add an icon, build a reusable Twig component or a Live Component, add Turbo Drive, Frames or Streams, write a Stimulus controller, organise templates or translation keys, or set a form theme. Also use it for the failures: "my JavaScript does not run", "my JS stopped working after clicking a link", "the CSS did not update", "the page is slow to load", "the assets 404 in production", "the images are served by PHP", "importmap:audit is failing" — and whenever the question is *where* a piece of behaviour belongs, between a Stimulus controller, a Live Component and a Twig Component./symfony-yoandev-httpWrite the HTTP layer of a Symfony application: controllers, routes, request input mapping, JSON and HTML responses, forms and Twig templates. One controller class per resource, a class-level route prefix, input DTOs hydrated by #[MapRequestPayload] or a FormType, output through #[Serialize] for JSON and #[Template] for HTML, RFC 7807 Problem Details for API errors, and an items + meta envelope for lists. Use this skill whenever someone asks to add a page, add a route or an endpoint, expose something as JSON, build an API, make a CRUD, build or wire up a form, map an uploaded file off the request, read a query parameter, paginate a list, return a 404 or a 422, protect an action with a CSRF token, render or restructure a Twig template, or says their endpoint returns a 500, their form never validates, their JSON has the wrong shape, or their route matches the wrong action. For what then happens to that uploaded file — where it is stored, how it is served back, who may read it — use `symfony-yoandev-storage` instead.Other plugins' skills for the same job