anantbhandarkar/make-it-right/mir-backend-php-symfony

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (Symfony module). Symfony 8.1 / 7.4 LTS + Doctrine ORM 3 + PostgreSQL/MySQL + Messenger + API Platform — mechanical reliability augmentation. Use alongside mir-backend and mir-backend-php when the target stack is Symfony; it carries the footguns the framework-agnostic tiers deliberately omit: Doctrine N+1 via lazy proxies, Unit of Work memory exhaustion in batch loops, the EntityManager closing after a failed flush, service-container singletons and ResetInterface under worker runtimes, Serializer normalization AND denormalization groups, Messenger with #[AsMessageHandler] and idempotent handlers, request-to-DTO mapping with #[MapRequestPayload]/#[MapQueryString]/#[MapUploadedFile], and the removal of Request::get() in Symfony 8. TRIGGER only when the PHP backend stack is Symfony — building, reviewing, or debugging a Symfony controller, Doctrine entity/repository, Messenger handler, Voter, migration, or DI service. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-php (Zend Engine runtime concerns: shared-nothing lifecycle, FPM worker model, worker-runtime state bleed, opcache/JIT, php.ini security, Composer supply chain); this module only adds Symfony/Doctrine library mechanics. SKIP for Laravel/Eloquent/Octane/Artisan work (that is mir-backend-php-laravel), for WordPress, Slim, or any non-Symfony PHP stack (each gets its own mir-backend-php-<framework> module), and for non-PHP runtimes.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-php-symfony

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-php-symfony.

/mir-backend-php-symfony · Make It Right (Symfony)

Bottom tier of the chain: mir-backend (generic gates) → mir-backend-php (Zend Engine runtime model) → this (Symfony/Doctrine library mechanics). Run the gates first; load the PHP runtime tier for the lifecycle/process model; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (shared-nothing lifecycle, FPM sizing, worker-runtime state bleed and superglobal resets, opcache/JIT, php.ini hardening, `unserialize`, Composer supply chain) live in `mir-backend-php` — not here.

Versions, verified 13 August 2026:

BranchStatusPHP minBug fixes untilSecurity until
8.1current stable (8.1.4, May 2026)8.4Jan 2027Jan 2027
8.0unmaintained since July 2026 (last 8.0.16)8.4endedended
7.4LTS (7.4.16, Nov 2025)8.2Nov 2028Nov 2029
6.4LTS, in maintenance8.1Nov 2026Nov 2027
5.4security fixes only7.2endedFeb 2029

7.4 and 8.0 shipped together in November 2025 with the same feature set — 8.0 is 7.4 minus the deprecated code, which is why an 8.0 project moves to 8.1 (not to 7.4) to get back on a maintained branch. 8.2 lands November 2026; the next LTS is 8.4 in November 2027.

Doctrine, verified 13 August 2026: ORM 3.6.8 (5 Aug 2026) with DBAL 4. ORM 2.x is in limited maintenance since March 2026 — only PHP-compatibility changes are merged. ORM 4 has not been released; its milestone is open with no date. ORM 3.4+ supports native lazy objects and property hooks.

Stack assumed: Symfony 8.1 or 7.4 LTS · Doctrine ORM 3 · PostgreSQL or MySQL · Symfony Messenger · API Platform (optional). If the project uses DBAL only (no ORM), a different message bus, or is still on ORM 2, note the divergence before applying these.

The Symfony/Doctrine footguns AI walks into most

1. Doctrine N+1 via lazy proxies — silent DB storm

Doctrine wraps unloaded associations in lazy-loading proxies. Accessing a proxy property ($order->getCustomer()->getName()) inside a loop triggers a SELECT per iteration — N orders produce N+1 queries. AI writes this constantly because the PHP looks correct.

  • Fix: make the join a fetch join by putting the joined alias in the SELECT. Doctrine DQL has no `FETCH` keyword — JPQL's JOIN FETCH is a syntax error here, and AI writes it constantly because the JPQL form dominates training data. The Doctrine docs are explicit: "There is no special DQL keyword that distinguishes a regular join from a fetch join. A join becomes a 'fetch join' as soon as fields of the joined entity appear in the SELECT part." In QueryBuilder that is addSelect() on the alias — a bare innerJoin without it still leaves a proxy. In API Platform, configure eager fetch on the relation or add the join in a custom extension.
  • Mapping-level fetch: 'EAGER' works for to-one associations and is a blunt instrument: it applies to every query, including ones that do not need the relation. Prefer per-query fetch joins.
php
// WRONG — N+1: one SELECT per $order->getCustomer()
$orders = $em->getRepository(Order::class)->findAll();
foreach ($orders as $order) {
echo $order->getCustomer()->getName(); // proxy fetch per row
}
// WRONG — `JOIN FETCH` is JPQL, not DQL. Doctrine throws a QueryException.
// $em->createQuery('SELECT o FROM App\Entity\Order o JOIN FETCH o.customer c');
// RIGHT — fetch join: `c` in the SELECT is what makes it eager. One query.
$orders = $em->createQuery(
'SELECT o, c FROM App\Entity\Order o JOIN o.customer c'
)->getResult();
// QueryBuilder equivalent — addSelect() is the part AI omits
$qb->select('o')->addSelect('c')
->from(Order::class, 'o')
->innerJoin('o.customer', 'c');

Fetch-joining a to-many collection breaks `setFirstResult`/`setMaxResults` — the row multiplication makes the limit apply to joined rows, not entities. Use Doctrine\ORM\Tools\Pagination\Paginator when you need both.

2. Unit of Work memory exhaustion in batch processing

The Unit of Work holds a reference to every managed entity it has seen since the EntityManager was created. In a batch loop — console command, Messenger handler, import script — it grows without bound until the process hits memory_limit.

  • Fix: flush() then clear() every chunk. clear() detaches everything so GC can reclaim it. Anything you still hold a variable to after clear() is now detached — calling flush() on it does nothing and lazy-loading from it throws. Re-fetch after clearing.
php
// WRONG — the UoW retains every Product; OOM after tens of thousands of rows
$products = $em->getRepository(Product::class)->findAll(); // 500k rows
foreach ($products as $product) {
$product->setUpdatedAt(new \DateTimeImmutable());
$em->persist($product);
}
$em->flush(); // also: one enormous transaction
// RIGHT — chunk with flush+clear; the UoW stays bounded
$batchSize = 500;
$i = 0;
$q = $em->createQuery('SELECT p FROM App\Entity\Product p')->toIterable();
foreach ($q as $product) {
$product->setUpdatedAt(new \DateTimeImmutable());
$em->persist($product);
if (++$i % $batchSize === 0) {
$em->flush();
$em->clear(); // detach all; GC can reclaim the prior batch
}
}
$em->flush();
$em->clear();

For read-only iteration add ->setHint(Query::HINT_READ_ONLY, true) to skip change tracking entirely. Also disable the SQL logger in long CLI runs — it buffers every query in memory.

3. EntityManager closed after an exception — the stale EM trap

When Doctrine catches a database exception during flush (constraint violation, deadlock, connection error) it closes the EntityManager. $em->isOpen() returns false and every subsequent ORM call throws "EntityManagerInterface is closed". AI code that catches the exception and keeps using the same instance produces cryptic errors on the next request or the next batch chunk.

  • Fix: inject ManagerRegistry, not EntityManagerInterface, in any service that has to survive a failed flush. resetManager() returns a fresh, open EM. Anything you were holding is detached — re-fetch it.
php
// WRONG — continues using a closed EM after a flush exception
try {
$em->flush();
} catch (\Throwable $e) {
$logger->error('Flush failed', ['e' => $e]);
// $em is closed — the next persist()/flush() throws
}
// RIGHT — reset so subsequent work gets a live instance
try {
$em->flush();
} catch (\Throwable $e) {
$logger->error('Flush failed', ['e' => $e]);
if (!$em->isOpen()) {
$em = $this->managerRegistry->resetManager(); // fresh, open EM
}
throw $e; // do not swallow
}

In a long-running messenger:consume worker this matters more than in a web request: one closed EM poisons every message after it until the worker restarts. Let the message fail and be retried rather than silently continuing with a broken EM.

4. Services are shared singletons — never store request state in them

Symfony's container creates services as shared by default — one instance for the process lifetime. Under FPM that is one request. Under FrankenPHP worker mode, Swoole, or RoadRunner the same instance handles many requests, and stored request state bleeds between users.

  • Fix first: pass request context as method arguments, DTOs, or value objects. A service with no state has nothing to leak.
  • When state is unavoidable: implement Symfony\Contracts\Service\ResetInterface. Symfony auto-tags such services kernel.reset and calls reset() between requests in worker mode. This is the current mechanism; shared: false is a blunter alternative that costs a new instance on every injection.
  • Symfony resets only what it knows about. Static properties, function-level static $x, and class-level caches are never reset by kernel.reset. Those are runtime-tier concerns — see mir-backend-php. And kernel.reset only fires if the runner actually calls it: a hand-rolled RoadRunner or Swoole loop resets nothing.
  • The EntityManager is the service that bites hardest here. Its identity map holds every entity the worker has touched, so under a worker runtime yesterday's tenant rows stay managed and memory climbs across requests; and a single failed flush() closes it for every subsequent request on that worker (§3), not just the one that failed. messenger:consume resets resettable services between messages unless you pass --no-reset; an HTTP worker runtime needs the equivalent clear-or-reset per request, plus resetManager() on the error path.
  • Symfony 8.1 escape hatch: FRANKENPHP_RESET_KERNEL=1 makes FrankenPhpWorkerRunner clone the application after each request so the next one starts from a freshly booted kernel. Use it when auditing every service is not realistic; it costs throughput.
php
// WRONG — the service stores the authenticated user as a property
class OrderService {
private User $currentUser;
public function setUser(User $u): void { $this->currentUser = $u; }
public function place(Cart $cart): Order { /* uses $this->currentUser */ }
}
// Under a worker runtime: request 1's user is still there for request 2
// RIGHT — pass it in; nothing is stored
class OrderService {
public function place(Cart $cart, User $actor): Order { /* pure */ }
}
// If state is genuinely required, make it resettable
class ImportBuffer implements \Symfony\Contracts\Service\ResetInterface {
private array $rows = [];
public function reset(): void { $this->rows = []; }
}
5. Serializer groups — both directions, not just output

The Serializer serializes every accessible property by default. Returning a full User entity can expose password, resetToken, stripeCustomerId, and internal timestamps. AI reliably remembers the output side and forgets the input side.

  • Output (`normalizationContext`): put #[Groups] on the properties you intend to expose and pass the group when serializing. #[Ignore] excludes a property from every group. AbstractNormalizer::IGNORED_ATTRIBUTES does it at call time.
  • Input (`denormalizationContext`) is the mass-assignment control. A group on the write side is what stops a client setting isAdmin or id. Without it, any property the denormalizer can write, it will write.
  • Unknown properties are silently ignored by default. AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES defaults to true, so a typo'd field is dropped with no error. Set framework.serializer.default_context.allow_extra_attributes: false to make it throw — it turns silent client bugs into 400s.
  • Never denormalize straight into a Doctrine entity. Denormalize into an input DTO and copy the fields you accept. Symfony 8's ObjectMapper component (now stable) is the supported way to map DTO → entity.
php
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\Ignore;
class User {
#[Groups(['user:read'])]
public int $id; // read-only: not in any write group
#[Groups(['user:read', 'user:write'])]
public string $email;
#[Ignore]
public string $password; // never serialized
#[Groups(['admin:read'])] // and NOT in user:write — clients cannot set it
public bool $isAdmin;
}
$json = $serializer->serialize($user, 'json', ['groups' => ['user:read']]);

In API Platform, declare normalizationContext and denormalizationContext per operation on #[ApiResource], and declare operations: explicitly — the default exposes the full CRUD set, DELETE included.

6. Messenger — #[AsMessageHandler], idempotency, and a failure transport

MessageHandlerInterface and MessageSubscriberInterface were removed in Symfony 7.0. Any code or generated snippet still implementing them will not work. Use the attribute.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-php-symfony/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-php-symfony)

Something wrong with this skill or its page? Tell us.