Lesson 4 of 9 · 28m
Doctrine ORM Without the Production Pain
Entities, repositories, migrations, Unit of Work, lazy loading, N+1 queries, and the transactional habits that keep Doctrine predictable.
Doctrine is not a database-shaped object factory. It is a Unit of Work and identity map wrapped around SQL. Teams get hurt when they treat entities as mutable bags, flush inside loops, or let lazy loading fire inside templates.
Entities model invariants, not tables
#[ORM\Entity]
class Order
{
#[ORM\Column]
private int $totalCents = 0;
public function addLine(int $priceCents, int $quantity): void
{
if ($quantity < 1) {
throw new DomainException('Quantity must be positive.');
}
$this->totalCents += $priceCents * $quantity;
}
}Meaningful methods protect consistency. A pile of setters lets every caller bypass the business rules that make the object coherent.
Flush once at the boundary
Doctrine tracks managed entities. Load, mutate, then flush once:
foreach ($imports as $row) {
$customer->rename($row['name']);
}
$em->flush();Flushing inside a loop creates partial failure modes and unnecessary transactions. Large imports need batching or queue jobs, not wishful ORM hydration.
The N+1 query is the classic failure
A template that reads order.customer.email for fifty orders can issue fifty extra queries. Fetch what the use case needs:
return $this->createQueryBuilder('o')
->addSelect('c')
->join('o.customer', 'c')
->where('o.createdAt > :since')
->setParameter('since', $since)
->getQuery()->getResult();For read-heavy screens, a dedicated DTO query is often better than hydrating an object graph to render a table.
Migrations are deploy artifacts
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate --dry-runGenerated migrations do not understand locking, backfills, or zero-downtime deploys. Large tables often need stages: add nullable column, deploy writers, backfill in batches, then enforce the constraint.
Field notes
- Use the profiler query panel; believe surprising query counts.
- Avoid
findAll()outside prototypes. Production data always grows. - Lazy loading inside Twig or serialization is a reliability bug, not a convenience.
flushis not automatically the boundary for external calls; design idempotency around payments and messages.- Doctrine rewards teams that inspect SQL. Refusing to look at generated SQL lets the ORM drive the team.
Was this lesson helpful?