Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Doctrine ORM Deep Dive - Foundation, Best Pract...

Doctrine ORM Deep Dive - Foundation, Best Practices & Advanced Features

Doctrine ORM is the de facto standard ORM in Symfony applications. In recent years Doctrine DBAL & ORM have seen new major releases and with that breaking changes and updated recommendations on their usage. In this wokshop we want to introduce you to current best practices with Doctrine ORM and DBAL, as well as a deep dive of some of the more advanced features in Doctrine. In a series of exercises in a demo application we will explore these functionalities in practice.

While this workshop does not focus on modernization/upgrading to the most recent major versions, we will discuss some of the breaking changes and how to tackle them, if this is relevant to participants. Please note, that basic familiarity with Symfony & Doctrine are assumed. If you have no prior experience with Doctrine (or similar ORMs), we will try to accommodate as best as we can.

Denis Brumann

November 24, 2026

Transcript

172 slides
  1. SYMFONYCON WARSAW 2026 · WORKSHOP Doctrine ORM: Deep Dive Foundation,

    Best Practices & Advanced Features Oliver Kossin & Denis Brumann · 24 November 2026 · Outline draft
  2. Your trainers Oliver Kossin Denis Brumann Symfony Developer at Denkwerk

    GmbH Solution Architect at Next Kraftwerke GmbH Part of the Sulu CMS core team for many years I spent hours step-debugging through UnitOfWork Your turn: introduce yourself • Who are you, and what do you work on? • How do you use Doctrine today? • What do you hope to take away from this workshop? Doctrine ORM: Deep Dive · Warsaw 2026
  3. The plan for the day Time What 09:00 – 09:30

    Welcome and introduction round: which topics matter to you? 09:30 – 10:45 Session 1 10:45 – 11:15 Coffee break 11:15 – 12:30 Session 2 12:30 – 13:30 Lunch break 13:30 – 15:00 Session 3 15:00 – 15:30 Coffee break 15:30 – 16:45 Session 4 16:45 – 17:00 Wrap-up. We finish at 17:00 We pick the topics together; every topic stays in the slides for reading later. Doctrine ORM: Deep Dive · Warsaw 2026
  4. The example project A quiz app for the workshop Questions

    of three kinds (single choice, multiple choice, free text) in tagged categories Quizzes bundle questions in a fixed order; users take them as attempts with a score Nine entities: User, Category, Tag, Question, AnswerOption, Quiz, QuizQuestion, QuizAttempt, QuestionResponse One repository per entity, attribute mapping, underscore naming; the exercises live in docs/excercises/ Stack and setup STACK Symfony 8.2 and PHP 8.5 Doctrine ORM 3.8 PostgreSQL 18 in Docker COMMANDS make start make db-fixtures GET THE CODE github.com/BibisCodingPalace/ doctrine-workshop-warsaw Doctrine ORM: Deep Dive · Warsaw 2026 · 01 URL localhost:8000
  5. Table of contents 01 The project and architecture 07 Batch

    processing Doctrine project structure 03 Debugging with the Debug Toolbar 1.1 7.1 Memory and batches 1.2 Architecture and patterns 3.1 Reading the toolbar 7.2 Bulk changes and tuning 1.3 Configuration 3.2 Checklist and beyond 1.4 Upgrade and migration 02 Basics: mapping and querying 08 Migrations 04 Caching 8.1 Writing migrations 4.1 Caching layers 8.2 Data and deployment 4.2 Result and second-level cache 2.1 Entities, types and identifiers 2.2 Associations and fetching 2.3 Structure and best practices 2.4 Writing queries 2.5 Pagination and security 06 Locking 2.6 Results and hydration 6.1 The lost update 2.7 Partial data 6.2 Pessimistic locking 2.8 Transactions and the DBAL 🧪 🧪 🧪 9.1 Test setup 5.1 Lifecycle and flush events 9.2 Test data and test types 5.2 Listening to events · Wrap-up and resources Doctrine ORM: Deep Dive · Warsaw 2026 · 🧪 hands-on lab 🧪 🧪 09 Testing 05 Events 🧪 🧪 🧪
  6. SYMFONYCON WARSAW 2026 01 The project and architecture Know the

    moving parts before we touch them Doctrine ORM: Deep Dive · Warsaw 2026
  7. THE PROJECT AND ARCHITECTURE · 1.1 Project structure The Doctrine

    project · DBAL and ORM · Building blocks Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  8. The Doctrine project Package Role Current doctrine/orm Object-relational mapper 3.8

    doctrine/dbal Database abstraction layer 4.6 doctrine/migrations Schema versioning and deployment 3.9 doctrine/persistence Interfaces shared by all mappers 4.2 doctrine/collections Array-like collection objects 3.1 doctrine/event-manager Event system used across Doctrine 2.1 doctrine/lexer Parsing building block, used for DQL 3.1 doctrine/instantiator Creates objects without constructors 2.2 doctrine/data-fixtures Fixtures for all object managers 2.3 Doctrine ORM: Deep Dive · Warsaw 2026 · 01 · versions as of November 2026
  9. DBAL and ORM DBAL ORM Talks to the database, knows

    nothing about your objects Maps objects to rows, built on top of the DBAL Connection and driver abstraction Platforms for each database vendor Schema introspection and management Types and a QueryBuilder Usable without the ORM Doctrine ORM: Deep Dive · Warsaw 2026 · 01 Mapping of entities and associations EntityManager and UnitOfWork DQL, repositories and hydration Caching and lifecycle events Lazy loading of associations
  10. Building blocks, layer by layer Your code Controllers, services, commands

    You work at this level most of the day Doctrine ORM ↓ $em->getConnection() Entities, repositories, QueryBuilder, DQL, EntityManager, UnitOfWork gives you the DBAL connection Doctrine DBAL ↓ getNativeConnection() Connection, query builder, schema manager, types returns the PDO object PHP core PDO and the database extensions, such as pdo_mysql or pdo_pgsql ↓ Raw driver features, such as PDO attributes Across the ORM layers: ClassMetadata (your mapping), caches and events, covered later today Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  11. THE PROJECT AND ARCHITECTURE · 1.2 Architecture and patterns Data

    Mapper · Unit of Work · Flush · Entity states Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  12. Data Mapper: how the pieces fit Entity Plain PHP object:

    state and behavior, no database code persist() → ← find() Data Mapper EntityManager and UnitOfWork: track changes, then write and read ↑ reads the mapping Mapping metadata Attributes say how fields map to columns Doctrine ORM: Deep Dive · Warsaw 2026 · 01 SQL statements → ← rows Database Tables and rows
  13. Active Record vs Data Mapper Active Record (Eloquent) Data Mapper

    (Doctrine) class Product extends Model { protected $table = 'products'; } #[ORM\Entity] class Product { #[ORM\Column] private string $name; } $product = new Product(); $product->name = 'Keyboard'; $product->save(); The model extends a base class, knows its table and saves itself. Doctrine ORM: Deep Dive · Warsaw 2026 · 01 $product = new Product('Keyboard'); $em->persist($product); $em->flush(); A plain class with mapping metadata. The EntityManager saves it on flush.
  14. Compared with Active Record Aspect Active Record (Eloquent) Data Mapper

    (Doctrine) What saves the object The model: $model->save() The mapper: persist() and flush() Base class Extends a model class None, a plain class Knows its table The model itself Mapping metadata, kept separate Writes Each save() runs a query Collected, run together on flush Same row twice Two separate objects One object (identity map) Testing Usually needs a database Entities work without one Trade-off Less code, quick to start More setup, suits richer domains Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  15. Unit of Work and identity map $a = $em->find(Product::class, 1);

    $b = $em->find(Product::class, 1); var_dump($a === $b); // true $a->setName('New name'); $em->flush(); // UPDATE, only if changed Doctrine ORM: Deep Dive · Warsaw 2026 · 01 Two ideas behind flush The UnitOfWork tracks every managed entity On flush it compares each one to its loaded state It orders and runs all changes in one transaction The identity map keeps one object per row and manager
  16. What happens on flush Step by step 1. persist() and

    property changes only touch memory 2. flush() fires preFlush , then compares each managed entity to its original data 3. onFlush fires; changes are ordered 4. All inserts, updates and deletes run in one transaction 5. postFlush fires when the work is done Doctrine ORM: Deep Dive · Warsaw 2026 · 01 Why it matters Nothing is written before flush, and one flush is one transaction. This explains events, locking and batch processing later today.
  17. Entity states New Managed Detached Removed Created with new, unknown

    to Doctrine Tracked by the EntityManager, changes are found on flush Has an identity, but is no longer tracked Scheduled for deletion on the next flush persist() makes it managed Loaded or persisted detach() or clear() merge() is gone since ORM 3: load it again with find() Everything Doctrine does on flush depends on the state of your entities. Doctrine ORM: Deep Dive · Warsaw 2026 · 01 remove()
  18. Identity map vs queries Answered from the identity map $em->find()

    $em->getReference() $repository->find() Always query the database findBy(), findOneBy() count(), matching() DQL and the QueryBuilder Until you flush Queries do not see unflushed changes, but return the instance you modified Removed entities are still returned by queries A new entity is only found by find(), and only if its id is known before flush Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  19. THE PROJECT AND ARCHITECTURE · 1.3 Configuration Doctrine in Symfony

    · Reference configuration · Conveniences Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  20. Doctrine in Symfony Configuration Services • config/packages/doctrine .yaml • EntityManagerInterface

    • DBAL: connection, server version • ManagerRegistry • ORM: mappings, naming strategy • Repositories as services • Cache pools for each cache Doctrine ORM: Deep Dive · Warsaw 2026 · 01 via autowiring for many connections • Listeners registered with tags Tooling doctrine:schema:validate doctrine:mapping:info doctrine:migrations:diff and migrate Doctrine panel in the profiler
  21. Reference configuration doctrine: dbal: url: '%env(resolve:DATABASE_URL)%' profiling_collect_backtrace: '%kernel.debug%' orm: naming_strategy:

    doctrine.orm.naming_strategy.underscore auto_mapping: true mappings: App: type: attribute is_bundle: false dir: '%kernel.project_dir%/src/Entity' prefix: 'App\Entity' when@test: doctrine: dbal: dbname_suffix: '_test%env(default::TEST_TOKEN)%' Doctrine ORM: Deep Dive · Warsaw 2026 · 01 Key settings • Connection comes from an environment variable • profiling_collect_backtrace shows callers in the toolbar • Underscore naming for tables and columns • Attribute mapping in src/Entity • Test database gets its own name suffix
  22. Symfony conveniences #[Route('/product/{id}')] public function show(Product $product): Response { //

    fetched by id, 404 if missing } Beyond configuration #[Route('/product/{slug}')] public function bySlug( #[MapEntity(mapping: ['slug' => 'slug'])] Product $product, ): Response { // fetched by slug } • UniqueEntity Doctrine ORM: Deep Dive · Warsaw 2026 · 01 • #[MapEntity] fetches entities from route parameters • Options include id, mapping and expr is added for unique columns • Several entity managers through ManagerRegistry • Pick one with objectManager
  23. THE PROJECT AND ARCHITECTURE · 1.4 Upgrade and migration What

    is different today · Native lazy objects · ORM 2 to 3 · DBAL 3 to 4 Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  24. ORM 2.x vs 3.8: mapping Area ORM 2.x ORM 3.8

    Mapping Annotations, attributes or XML Attributes or XML Lazy loading Generated proxy classes Native lazy objects on PHP 8.4+ Entities Cannot be final (proxy subclasses) Can be final with native lazy objects AUTO on PostgreSQL Sequence or serial Identity columns (with DBAL 4) Partial objects PARTIAL for entities Back: arrays from 3.2, objects from 3.3 Change tracking Including NOTIFY Deferred implicit or explicit Detached entities merge() Removed, no replacement Second-level cache Doctrine Cache PSR-6 cache pools Partial flush flush($entity) flush() takes no arguments Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  25. ORM 2.x vs 3.8: querying Area ORM 2.x ORM 3.8

    Large reads Query::iterate() toIterable() Transactions transactional() wrapInTransaction() Named queries Supported Removed Bootstrap EntityManager::create() , Setup new EntityManager() , ORMSetup Pagination Paginator Offset and cursor paginators Sort directions 'ASC' and 'DESC' strings DQL joins JOIN ... WITH JOIN ... ON for arbitrary joins Code generators orm:generate:entities Removed Date and time Plain datetime types UTC types (introduced in DBAL 4.5) mutable types deprecated (4.6) Doctrine ORM: Deep Dive · Warsaw 2026 · 01 SortDirection enum (findBy() still takes strings)
  26. Upgrading DBAL 3 to 4 Look out for • PDO

    is no longer exposed directly • Fix deprecations on the latest 3.x first • Use the driver and connection options, not raw PDO calls Reaching the driver // DBAL 3 $pdo = $connection->getWrappedConnection(); // DBAL 4 $pdo = $connection->getNativeConnection(); • Removed deprecated types such as array • Custom types and platforms need review Keep in mind The native connection is only for escape hatches. Prefer the DBAL API for queries and transactions. Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  27. Upgrading ORM 2 to 3 Look out for • Annotations

    become PHP attributes • Fix deprecations on the latest 2.x first • Removed methods such as merge() • Step by step: DBAL 3, then ORM 3, then DBAL 4 rector.php use Rector\Config\RectorConfig; return RectorConfig::configure() ->withPaths([__DIR__ . '/src']) ->withAttributesSets(doctrine: true); • Stricter types in extension points • Enable the new schema editor API (3.8) After the run Rector converts the mapping annotations in bulk. Review the diff and run the tests afterwards. Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  28. Prepare an upgrade: find deprecations Where they show up •

    Doctrine turns them into .env.local DOCTRINE_DEPRECATIONS=trigger E_USER_DEPRECATED with DOCTRINE_DEPRECATIONS=trigger • Symfony web profiler: the Deprecations panel, per request • PHP error log or container output phpunit.dist.xml <phpunit failOnDeprecation="true"> <source ignoreIndirectDeprecations="true"> • PHPUnit with failOnDeprecation Keep in mind Deprecations are only reported for code that actually runs. Doctrine ORM: Deep Dive · Warsaw 2026 · 01
  29. Why it is easy to miss No logging Only per

    request Tests stay green Without a logging setup, PHP defaults print the notice to the container output, and nowhere else. The profiler lists deprecations for the page you just opened. Pages nobody opens stay silent. Notices raised inside vendor code count as indirect. With What to do • Look for deprecations on purpose, before you upgrade • Run the tests regularly with ignoreIndirectDeprecations disabled, in CI/CD • Log deprecations in production Doctrine ORM: Deep Dive · Warsaw 2026 · 01 ignoreIndirectDeprecations the build passes, although the cause is your own attribute.
  30. Upgrade preparation checklist Before you change a major version Watch

    out 1. • Indirect deprecations can still be your code Update to the latest release of the current major 2. Make deprecations visible: profiler, logs, DOCTRINE_DEPRECATIONS 3. Run the tests, click through the app, run console commands 4. Fix what your own code triggers first 5. For vendor-triggered ones, look for a newer release 6. Fail the build on deprecations in CI 7. Then upgrade the major version Doctrine ORM: Deep Dive · Warsaw 2026 · 01 • Untested code paths report nothing • Fix in small commits, one deprecation at a time
  31. Lab: from request to SQL Tasks Clone the playground, run

    make start, then make db-fixtures Open localhost:8000 and check the Doctrine panel in the toolbar Find the controller, repository and query behind it Run doctrine:mapping:info and doctrine:schema:validate Sketch the path from controller to SQL Doctrine ORM: Deep Dive · Warsaw 2026 · 01 Goal Everyone has a running project and knows where each layer shows up.
  32. SYMFONYCON WARSAW 2026 02 Basics: mapping and querying From entity

    to table, and from query to object Doctrine ORM: Deep Dive · Warsaw 2026
  33. BASICS: MAPPING AND QUERYING · 2.1 Entities, types and identifiers

    An entity with attributes · Field types · Dates · Identifiers Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  34. An entity with attributes #[ORM\Entity(repositoryClass: ProductRepository::class)] #[ORM\Table(name: 'product')] class Product

    { #[ORM\Id, ORM\GeneratedValue] #[ORM\Column(options: ['unsigned' => true])] private ?int $id = null; #[ORM\Column(length: 120)] private string $name; #[ORM\Column(enumType: ProductStatus::class)] private ProductStatus $status; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Good to know Attributes replace annotations The column type is inferred from the PHP type when possible The repository class is optional Backed enums map to a column of their value type Unsigned ids are set through the column options
  35. The Column attribute: all arguments #[ORM\Column( name: null, type: null,

    length: null, precision: null, scale: null, unique: false, nullable: false, insertable: true, updatable: true, enumType: null, options: [], columnDefinition: null, generated: null, index: false, )] Doctrine ORM: Deep Dive · Warsaw 2026 · 02 // column name, default: the property name // DBAL type, guessed from the property type // maximum length of string columns // decimal: total number of digits // decimal: digits after the decimal point // add a unique constraint // allow NULL values // include the column in INSERT statements // include the column in UPDATE statements // backed enum class for the value // unsigned, default, fixed, comment, charset, collation, values // raw DDL snippet, not portable // database-generated: NEVER, INSERT or ALWAYS // create an index on the column
  36. Field types DBAL type PHP type Use for string, ascii_string,

    text string Names, codes, long text integer, smallint int Counters, sizes bigint int, or string if too large Very large numbers decimal string Money, exact numbers boolean bool Flags datetime_immutable DateTimeImmutable Timestamps datetime_utc_immutable DateTimeImmutable (UTC) Timestamps in UTC json, jsonb array Flexible, rarely queried data enumType option backed enum Statuses, categories Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  37. Removed and deprecated types Type Status Use instead array (ArrayType)

    Removed in DBAL 4 json, or a dedicated table object (ObjectType) Removed in DBAL 4 json, or an embeddable value object json_array Removed in DBAL 3 json simple_array Deprecated in DBAL 4.5 json Mutable date and time types Deprecated in DBAL 4.6 The *_immutable variants Upgrading existing data Old columns hold PHP-serialized strings. Convert them to JSON in a migration before you change the mapping, and never unserialize untrusted data. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  38. Working with dates #[ORM\Column(type: Types::DATETIME_IMMUTABLE)] private DateTimeImmutable $createdAt; // Change

    by replacing, not modifying $order->setPaidAt( new DateTimeImmutable('now', $utc) ); Dates without surprises • Use immutable types; mutable ones are deprecated in DBAL 4.6 • Mutating a DateTime in place can go unnoticed • Store UTC and convert only for display // Compare with operators, not === if ($order->getPaidAt() < $deadline) { // ... } • Set time zones explicitly, not by PHP default • datetime_utc_immutable enforces UTC (DBAL 4.5) Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  39. Identifiers Strategy Id is created by Consequence AUTO Platform default

    Sequence or identity, depending on the database IDENTITY Auto-increment column Id is known only after the INSERT SEQUENCE Database sequence Id can be fetched before inserting NONE Your code Assigned identifiers: set the id before persist() CUSTOM A generator class UUIDs or ULIDs, for example from Symfony UID Random UUIDs make indexes larger and less local; ULIDs sort by time. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  40. Symfony UID as identifier use Symfony\Bridge\Doctrine\Types\UuidType; use Symfony\Component\Uid\Uuid; Why this

    works • Id exists before persist(), #[ORM\Entity] class Product { #[ORM\Id] #[ORM\Column(type: UuidType::NAME)] private Uuid $id; public function __construct() { $this->id = Uuid::v7(); } } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 no database round trip • Uuid::v7() sorts by time, so indexes stay compact • Use UlidType for ULIDs • Stored natively or as 16 bytes, depending on the platform
  41. BASICS: MAPPING AND QUERYING · 2.2 Associations and fetching Association

    types · ManyToOne · Lazy loading · Cascades Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  42. Association types Type Owning side Notes ManyToOne Always, holds the

    foreign key The workhorse, cheap to load OneToOne The side with the foreign key Inverse side cannot be lazy OneToMany Never, inverse of a ManyToOne Needs mappedBy and a collection ManyToMany Either side, owner has the join table Often better as an explicit entity Avoid the inverse side where you can Every inverse side is a collection to keep in sync, and touching it can load far more rows than you need. Query the many side through a repository instead. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  43. Associations class Product { #[ORM\ManyToOne(inversedBy: 'products')] #[ORM\JoinColumn(nullable: false)] private Category

    $category; } class Category { #[ORM\OneToMany( targetEntity: Product::class, mappedBy: 'category', )] private Collection $products; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Owning and inverse side • The owning side holds the foreign key and is the one Doctrine writes • The inverse side (mappedBy) mirrors it • Keep both sides in sync in your methods • targetEntity is inferred only for to-one typed properties
  44. ManyToOne without an inverse side class Invoice { #[ORM\ManyToOne] #[ORM\JoinColumn(nullable:

    false)] private Customer $customer; } // Customer has no $invoices collection // InvoiceRepository public function findRecent(Customer $customer): array { return $this->findBy( ['customer' => $customer], ['issuedAt' => 'DESC'], 20, ); } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 What you handle yourself • Load invoices with a filtered, limited query • No cascade or orphanRemoval from the customer • Deleting a customer with invoices fails on the foreign key • Or let the database cascade with onDelete
  45. Fetching and lazy loading fetch option Behavior Watch out for

    LAZY Loaded on first access (default) N+1 queries EAGER Loaded together with the owner Loads data you may not need EXTRA_LAZY count(), contains() and slice() without loading everything Only for collections Fetch join in DQL A query, not a mapping option SELECT p, c FROM App\Entity\Product p JOIN p.category c Selecting the joined alias loads the association in the same query. Paginate joined collections with care. On PHP 8.4, native lazy objects replace generated proxy classes. DoctrineBundle 3.x always enables them. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  46. Cascades and orphans cascade orphanRemoval onDelete Passes operations like persist

    and remove from an entity to its associations, so children do not need their own calls. Deletes a child once it is removed from its parent's collection. Use it only for children that belong to one parent. A database-level cascade on the join column. It is fast, but the ORM and its events do not see the deleted rows. The best practices page advises using cascades judiciously. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  47. BASICS: MAPPING AND QUERYING · 2.3 Structure and best practices

    Embeddables · Inheritance · Best practices · Known gotchas Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  48. Embeddables #[ORM\Embeddable] class Money { #[ORM\Column(type: 'integer')] private int $amount;

    Value objects • Columns live in the owner's table: price_amount, price_currency • No identity of their own • columnPrefix #[ORM\Column(length: 3)] private string $currency; } // inside the entity #[ORM\Embedded(class: Money::class)] private Money $price; Doctrine ORM: Deep Dive · Warsaw 2026 · 02 is optional: it controls the column names • DQL reaches inside: p.price.amount
  49. Embeddables: column prefixes false null (default) string #[ORM\Embedded( class: Money::class,

    columnPrefix: false )] private Money $price; #[ORM\Embedded( class: Money::class, columnPrefix: null )] private Money $price; #[ORM\Embedded( class: Money::class, columnPrefix: 'cost_' )] private Money $price; // amount, currency // price_amount, price_currency // cost_amount, cost_currency No prefix. The columns are named exactly like the embeddable fields. The prefix comes from the property name, through the naming strategy. Your own prefix goes in front of every column name. Add the underscore yourself. With false, embedding the same class twice in one entity makes the column names collide. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  50. Inheritance Strategy Tables Trade-off Mapped superclass None for the parent

    Shares mapping only; not queryable, not a target of associations Single table One, with a discriminator Fast queries, nullable columns for subclass fields Class table One per class, joined Normalized, but joins on every query Start with a mapped superclass or composition, and use table inheritance only when you query the base type. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  51. Mapped superclass: example #[ORM\MappedSuperclass] abstract class Auditable { #[ORM\Column] protected

    DateTimeImmutable $createdAt; #[ORM\Column] protected DateTimeImmutable $updatedAt; } Shared mapping, no table • The superclass is not an entity: no table, not queryable • Its fields become columns of every subclass table • It needs no identifier of its own • It cannot be the target of an association #[ORM\Entity] class Product extends Auditable { #[ORM\Id, ORM\GeneratedValue, ORM\Column] private ?int $id = null; #[ORM\Column] private string $name; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  52. Single table inheritance: example #[ORM\Entity] #[ORM\InheritanceType('SINGLE_TABLE')] #[ORM\DiscriminatorColumn(name: 'type', type: 'string')]

    #[ORM\DiscriminatorMap([ 'card' => CardPayment::class, 'paypal' => PayPalPayment::class, ])] abstract class Payment { // id, amount } #[ORM\Entity] class CardPayment extends Payment { #[ORM\Column(length: 4, nullable: true)] private ?string $lastFour = null; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 One table, one discriminator • One table holds the whole hierarchy • The discriminator column tells the ORM which class to create • Subclass columns must be nullable • No joins, just a WHERE on the type: fast, but a wide table
  53. Class table inheritance: example #[ORM\Entity] #[ORM\InheritanceType('JOINED')] #[ORM\DiscriminatorColumn(name: 'type', type: 'string')]

    #[ORM\DiscriminatorMap([ 'card' => CardPayment::class, 'paypal' => PayPalPayment::class, ])] abstract class Payment { // id, amount } #[ORM\Entity] class CardPayment extends Payment { #[ORM\Column(length: 4)] private string $lastFour; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 One table per class • Each class has its own table, linked by the id • Subclass columns can be NOT NULL • Almost every query joins parent and child tables • Querying the base class means LEFT JOINs to all subtypes
  54. Lab: map the question catalog Exercise 1 · 01-mapping.md 1.

    2. 3. 4. 5. Category with a self-referencing tree ( parent , children ) and a unique slug Tag and the string-backed Difficulty enum Abstract Question with SINGLE_TABLE and three subtypes Question relations: category, tags, answerOptions; then AnswerOption Run make db-update-schema and read the generated migration Watch out Verify • The child side of the tree uses inversedBy , the collection • make test passes mappedBy • Subtype columns become nullable on the shared table • sortOrder is a SMALLINT, not a plain INT Doctrine ORM: Deep Dive · Warsaw 2026 · 02 • A test persists the graph, clears the EM and re-fetches the right subclasses
  55. Best practices from the docs Constrain relations Avoid composite keys

    Map only the associations you really navigate. They complicate entities and caching. Events and cascades sparingly Collections in the constructor Both hide work from the reader of the code. Initialize them so they are never null. No foreign keys as fields Explicit transactions Map the association, not the id column. Mark transaction boundaries yourself. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  56. Typical gotchas Only the owning side is saved A failed

    flush closes the manager Setting just the inverse side changes nothing in the database. After an exception, create a fresh EntityManager. Bulk DQL bypasses the identity map Limit plus to-many fetch join Loaded entities go stale, and no events fire. LIMIT cuts rows, not entities. Use the OffsetPaginator. Changes inside onFlush Memory grows in loops Recompute the change set yourself, or they are lost. Managed entities stay in memory until you call clear(). Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  57. Lab: reconcile a collection Exercise 2 · 04-collection-reconciliation.md 1. 2.

    3. 4. Open Admin\QuizController::reconcileQuizQuestions() Edit a quiz and keep one question selected: the page returns a 500 Read the UniqueConstraintViolationException (SQLSTATE 23505) Replace remove-all and add-all with a diff of old and new selection Still selected: update sortOrder in place · newly selected: addQuestion() · deselected: removeQuestion() Watch out Verify • A DELETE and an INSERT of the same pair in one flush hit • testEditingAQuizUpdatesFieldsAndQuestionSelection UNIQ_QUIZ_QUESTION • A second flush only hides the symptom • removeQuestion() compares by identity: look up by question id Doctrine ORM: Deep Dive · Warsaw 2026 · 02 passes • Clear and re-add is still safe for AnswerOption : no unique pair there
  58. Lab: the QuizAttempt aggregate Exercise 3 · 06-quiz-attempt-aggregate.md 1. 2.

    3. 4. 5. Read QuizAttempt , QuestionResponse and the embeddable Score Stub the loop in QuizAttemptController::submit() , keep gradeQuestion() Create a QuestionResponse per question and add it with $attempt->addResponse() Tally correct count and points, then $attempt->complete(new Score(...)) Flush once and take a quiz in the browser Watch out Verify • No persist() on the responses: the cascade does it • make test , including • Each Score column needs its own nullable: true • Uuid::v7() keeps inserts ordered, v4 scatters them Doctrine ORM: Deep Dive · Warsaw 2026 · 02 testResubmittingACompletedAttemptDoesNotRegrade • The id is a UUID string; unfinished attempts have a NULL final score
  59. BASICS: MAPPING AND QUERYING · 2.4 Writing queries Repositories ·

    QueryBuilder · DQL · Native SQL · DBAL directly Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  60. Querying Topics • Repositories: find, findBy, custom methods • QueryBuilder

    and DQL, joins and fetch joins • Native SQL with result set mapping • Transactions and what flush() does • DBAL underneath: Connection and its QueryBuilder • Pagination: offset and cursor Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Hands-on lab Write the same query as QueryBuilder, DQL and native SQL
  61. Repositories Built in find($id) findAll() findBy($criteria, $orderBy, $limit) findOneBy($criteria) count($criteria)

    Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Your own • Extend ServiceEntityRepository • One named method per use case • Keep queries out of controllers • Prefer explicit methods over magic findByName() calls
  62. QueryBuilder $qb = $this->createQueryBuilder('p') ->join('p.category', 'c') ->addSelect('c') ->where('c.name = :name')

    ->andWhere('p.price > :min') ->setParameter('name', $name) ->setParameter('min', $min) ->orderBy('p.name'); return $qb->getQuery()->getResult(); Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Building queries • Composes DQL step by step • Always bind parameters, never concatenate • addSelect() with a join fetches the association • Good for optional filters
  63. DQL SELECT p, c FROM App\Entity\Product p JOIN p.category c

    WHERE p.price > :min ORDER BY p.name $query = $em->createQuery($dql) ->setParameter('min', '10.00') ->setMaxResults(20); Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Objects, not tables Names entities and properties, not tables and columns SELECT, UPDATE and DELETE Translated to SQL and cached Functions, aggregates, BETWEEN, IN, LIKE Select the root entity when selecting others
  64. Native SQL $rsm = new ResultSetMappingBuilder($em); $rsm->addRootEntityFromClassMetadata( Product::class, 'p' );

    $select = $rsm->generateSelectClause(['p' => 'p']); $sql = "SELECT $select FROM product p WHERE p.price > ?" ; $products = $em->createNativeQuery($sql, $rsm) ->setParameter(1, '10.00') ->getResult(); Doctrine ORM: Deep Dive · Warsaw 2026 · 02 When DQL is not enough Vendor-specific features Complex reports Still returns managed entities No entities needed? Use the DBAL directly
  65. Using the DBAL directly $conn = $em->getConnection(); $rows = $conn->fetchAllAssociative(

    'SELECT id, name FROM product WHERE price > ?', ['10.00'] ); // array of arrays, not Product entities // e.g. ['id' => 1, 'name' => 'Pen'] $conn->executeStatement( 'UPDATE product SET price = price * 1.1' ); // int: number of affected rows, // nothing is hydrated Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Below the ORM • fetchOne, fetchAssociative, fetchAllAssociative, executeStatement • DBAL QueryBuilder, with FULL JOIN since 4.5 • No entities, events or change tracking
  66. BASICS: MAPPING AND QUERYING · 2.5 Pagination and security Pagination

    · SQL filters · User input Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  67. Pagination OffsetPaginator • Page numbers and random access • Extra

    COUNT, only when you ask for the total • Deep pages get slow • Pages shift when rows are added or deleted • Set fetchJoinCollection for joined collections Doctrine ORM: Deep Dive · Warsaw 2026 · 02 CursorPaginator Previous and next only Stable results under changes Constant speed on large tables Uses an index range scan
  68. Pagination in practice Cursor rules A deterministic ORDER BY is

    mandatory Add a unique tie-breaker, usually the id Keep one sort direction for all columns Cursors are encoded strings for URLs Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Page API getItems() getTotalCount() hasNextPage() hasPreviousPage() Watch out The total runs an extra COUNT on first use Composite keys and secondlevel cache have limits Older code still uses the legacy Paginator
  69. SQL filters class SoftDeleteFilter extends SQLFilter { public function addFilterConstraint(

    ClassMetadata $targetEntity, string $targetTableAlias, ): string { if (!$targetEntity->hasField('deletedAt')) { return ''; } return $targetTableAlias . '.deleted_at IS NULL'; } } $em->getFilters()->enable('soft_delete'); Doctrine ORM: Deep Dive · Warsaw 2026 · 02 One rule for every query • Adds a SQL condition to every query for the entity • Typical uses: soft delete and multi-tenancy • Enable it in doctrine.yaml or at runtime • Not applied to native SQL or the DBAL • Easy to forget it is active
  70. Security: user input // Unsafe: input becomes part of the

    query $dql = "SELECT p FROM App\Entity\Product p WHERE p.name = '$name'"; Rules of thumb • Bind values with setParameter() • Never concatenate input into DQL // Safe: input is a bound parameter $query = $em->createQuery( 'SELECT p FROM App\Entity\Product p WHERE p.name = :name' ) ->setParameter('name', $name); // Identifiers cannot be parameters: // whitelist column and direction $column = in_array($sort, ['name', 'price']) ? $sort : 'name'; Doctrine ORM: Deep Dive · Warsaw 2026 · 02 • Whitelist sort columns and directions • Escape % and _ in LIKE patterns • Do not copy request data straight onto entities
  71. BASICS: MAPPING AND QUERYING · 2.6 Results and hydration Result

    methods · Hydration modes · Custom hydrators Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  72. Results and hydration Topics • Result methods and hydration modes

    • Object, array and scalar hydration • Reading large results lazily with toIterable() Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  73. Getting results Method Returns Throws getResult() List of results Nothing

    getSingleResult() Exactly one result No result or not unique getOneOrNullResult() One result or null Not unique getArrayResult() Arrays instead of objects Nothing getScalarResult() Flat rows of values Nothing getSingleScalarResult() One value, like a COUNT No result or not unique getSingleColumnResult() List of one column MultipleSelectorsFoundException toIterable() Rows one at a time (lazy) Nothing Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  74. Hydration modes Mode You get Cost HYDRATE_OBJECT Managed entities Highest

    HYDRATE_SIMPLEOBJECT Entities, no joins Lower HYDRATE_ARRAY Nested arrays Low HYDRATE_SCALAR Flat rows Low HYDRATE_SCALAR_COLUMN List of values Minimal HYDRATE_SINGLE_SCALAR One value Minimal Only object hydration puts entities under the UnitOfWork's control. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  75. Custom hydrators final class KeyValueHydrator extends AbstractHydrator { protected function

    hydrateAllData(): array { $this->hydrateAllRows(); return $this->takeResult(); } protected function hydrateRow(array $row): void { [$key, $value] = array_values( $this->gatherScalarRow($row), ); $this->hydrationResult[$key] = $value; } } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Register and use doctrine: orm: hydrators: key_value: App\Hydrator\KeyValueHydrator • getResult('key_value') • Fill $hydrationResult in hydrateRow() (ORM 3.8) • Often NEW with a DTO is simpler
  76. BASICS: MAPPING AND QUERYING · 2.7 Partial data SELECT NEW

    · DTOs · Partial objects Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  77. Fetching less than entities Approach Returns Use it for getArrayResult()

    Arrays of values Reports and read-only lists SELECT NEW DTO objects Read models with a fixed shape SELECT PARTIAL Entities, some fields loaded Loading less, with caveats DBAL fetch methods Plain arrays No entities involved Entities are the default. When you only need some data, ask for less. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  78. Fetching into a DTO: SELECT NEW final readonly class ProductRow

    { public function __construct( public int $id, public string $name, public string $category, ) { } } $rows = $em->createQuery( 'SELECT NEW App\Dto\ProductRow(p.id, p.name, c.name) FROM App\Entity\Product p JOIN p.category c' )->getResult(); Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Read models • Select only the columns a page needs • Any class with a matching constructor works, it does not need to be mapped • Results are plain objects: not managed, no change tracking • Arguments: scalar expressions, NULL or other DTOs • Aggregates work too, for example SUM with GROUP BY
  79. NEW NAMED and nested DTOs SELECT NEW NAMED App\Dto\CustomerDTO( a.city,

    c.name, CONCAT(a.city, ' ', a.zip) AS value ) FROM App\Entity\Customer c JOIN c.address a SELECT NEW App\Dto\CustomerDTO( c.name, NEW App\Dto\AddressDTO(a.street, a.city, a.zip) ) FROM App\Entity\Customer c JOIN c.address a Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Beyond positional arguments • NAMED matches arguments by name or alias, in any order • Alias function results with AS , or a NoMatchingPropertyException is thrown • Duplicate names throw a DuplicateFieldException • NEW can be nested to build DTOs inside DTOs
  80. Partial objects across versions ORM What changed 2.0 PARTIAL u.{id,

    name} is the explicit syntax; partial objects are off by default 2.2 Fields a partial query did not load are never written back 2.9 PARTIAL is deprecated in DQL (ORM issue 8471) 2.17 getPartialReference() is deprecated 2.20 PARTIAL is undeprecated: it comes back with PHP 8.4 lazy objects 3.0 PARTIAL , getPartialReference() and the force-partial hint are removed 3.2 / 3.3 Back for array hydration in 3.2, for arrays and objects from 3.3 3.4 Native lazy objects arrive for PHP 8.4 3.7 On PHP 8.4, partial objects load as lazy ghosts Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  81. Partial objects: curly braces in DQL $q = $em->createQuery( 'SELECT

    PARTIAL u.{id, name} FROM App\Entity\User u' ); $users = $q->getResult(); // User objects: only id and name loaded // Also possible with joins 'SELECT PARTIAL u.{id, name}, PARTIAL o.{id, total} FROM App\Entity\User u JOIN u.orders o' Warning: fragile objects • Objects with broken invariants: code must know which fields are safe to read • Without native lazy objects, unloaded fields are not updated by the unit of work, even if you change them • A NULL association could mean absent or not loaded • Promote to a full object only with refresh() • Mainly an optimization: do not use it prematurely Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  82. Partial objects on PHP 8.4 // Native lazy objects enabled,

    PHP 8.4+ $user = $em->createQuery( 'SELECT PARTIAL u.{id, name} FROM App\Entity\User u' )->getSingleResult(); Lazy ghosts echo $user->name; // loaded field: no extra query • After that the object is a normal entity echo $user->email; // not loaded: triggers a SELECT // for the full entity Doctrine ORM: Deep Dive · Warsaw 2026 · 02 • Only the listed fields are loaded eagerly • First access to any other field loads the full entity • The usual caveats no longer apply, so the partial load becomes a pure optimization • Requires native lazy objects to be enabled
  83. DTO or partial object? DTO with SELECT NEW PARTIAL objects

    • Explicit shape, no invariants to break • Still entities of your mapped class • Works on every PHP version • Safe only with native lazy objects • Not managed: read-only use • Extra query when other fields are touched • Needs a class per use case • Also allowed with array hydration Recommendation: Prefer DTOs, or plain arrays for simple read-only data. Use PARTIAL only with native lazy objects. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  84. BASICS: MAPPING AND QUERYING · 2.8 Transactions and the DBAL

    Transactions · Atomic updates · refresh() vs clear() Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  85. Transactions $em->wrapInTransaction( function () use ($em, $order) { $order->markPaid(); $em->persist(new

    Payment($order)); } ); Rules of thumb • Each flush() already runs in a transaction • The docs recommend explicit transaction demarcation • An exception during flush() closes the EntityManager • Manual control: beginTransaction, commit, rollBack on the connection Coming from an older version? wrapInTransaction() replaces transactional() , which was removed in ORM 3. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  86. Manual transaction control $conn = $em->getConnection(); $conn->beginTransaction(); Same result, more

    code • Call flush() inside the try block try { $order->markPaid(); $em->persist(new Payment($order)); $em->flush(); $conn->commit(); } catch (Throwable $e) { $conn->rollBack(); $em->close(); throw $e; } Doctrine ORM: Deep Dive · Warsaw 2026 · 02 • Roll back and rethrow on any error • Close the EntityManager after a failure • wrapInTransaction() does all of this for you
  87. Atomic updates and deletes Update with a condition Delete by

    condition $affected = $em->createQueryBuilder() ->update(Product::class, 'p') ->set('p.stock', 'p.stock - 1') ->where('p.id = :id') ->andWhere('p.stock > 0') ->setParameter('id', $id) ->getQuery() ->execute(); $deleted = $em->createQueryBuilder() ->delete(Session::class, 's') ->where('s.expiresAt < :now') ->setParameter('now', new DateTimeImmutable()) ->getQuery() ->execute(); if ($affected === 0) { // sold out } One statement, evaluated by the database, returns the affected row count. It skips events and versioning, so clear or refresh entities you already loaded. Doctrine ORM: Deep Dive · Warsaw 2026 · 02
  88. Stale state: refresh() vs clear() $product = $em->find(Product::class, $id); //

    stock changed by a bulk update // or through the DBAL connection $em->refresh($product); // $product is current again $em->clear(); // or detach everything at once Doctrine ORM: Deep Dive · Warsaw 2026 · 02 Watch out Refresh overwrites unflushed changes on that entity Associations refresh only when mapped with cascade refresh Clear is the better choice in loops and after many bulk operations
  89. SYMFONYCON WARSAW 2026 03 Debugging with the Debug Toolbar See

    what Doctrine really does Doctrine ORM: Deep Dive · Warsaw 2026
  90. DEBUGGING WITH THE DEBUG TOOLBAR · 3.1 Reading the toolbar

    The Doctrine panel · Spotting N+1 queries Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  91. Debug Toolbar and Profiler Topics Doctrine panel: query count, time

    and parameters Spotting N+1 queries and duplicate queries Running EXPLAIN on a query from the profiler Mapping information and schema validation Profiling requests and console commands Doctrine ORM: Deep Dive · Warsaw 2026 · 03 Hands-on lab Find and fix a planted N+1 problem
  92. The Doctrine panel In the toolbar Number of queries Total

    time spent in the database Click to open the full panel in the profiler Doctrine ORM: Deep Dive · Warsaw 2026 · 03 In the panel Every query with time and parameters Formatted and runnable SQL EXPLAIN for a single query Similar statements grouped with counts Mapping All mapped entities Invalid entities flagged in red Mapping checks only, not the database
  93. The Doctrine panel in action What to look at •

    11 queries for one page, but only 4 different statements: repeats are the N+1 sign • Group similar statements shows which ones repeat • Every query offers formatted, runnable, EXPLAIN and backtrace views • 25 managed entities are tracked by the unit of work Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  94. Spotting N+1 queries Before: N+1 queries After: 1 query $products

    = $repo->findAll(); SELECT p, c FROM App\Entity\Product p JOIN p.category c foreach ($products as $p) { echo $p->getCategory()->getName(); } In the toolbar: a high query count on one page, with many near-identical queries. Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  95. DEBUGGING WITH THE DEBUG TOOLBAR · 3.2 Checklist and beyond

    A checklist for every page · Beyond the toolbar Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  96. A checklist for every page How many queries? Identical queries?

    Does the count grow with the number of rows shown? The same statement multiple times is a candidate for a join or a cache. Slow queries? Too much data? Run EXPLAIN and look for full table scans and missing indexes. Entities loaded only to show few fields call for a DTO. Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  97. Beyond the toolbar Logging DBAL 4 logs through middleware; the

    old SQLLogger is gone The middleware stays on the connection: mute the PSR logger instead Log queries in dev or staging, not in every production request Doctrine ORM: Deep Dive · Warsaw 2026 · 03 Console commands Add --profile -v to any command in dev Output ends with See profile and the token Open it in /_profiler like a web request The database Slow query log and EXPLAIN on the real engine Test with productionsized data
  98. Lab: N+1 with a DTO Exercise 4 · 02-query-optimization.md 1.

    2. 3. 4. Open / and note the baseline in the Doctrine panel: 4 queries Create QuizSummary : a plain class, not mapped Write findPublishedSummaries() with SELECT NEW , LEFT JOIN , COUNT(qq.id) , GROUP BY q.id Use it in QuizController::index() and quiz.questionCount in the template Watch out Verify • COUNT(qq.id) , not COUNT(*) , so empty quizzes report 0 • The toolbar shows 1 query, also with a fourth quiz • Constructor arguments are positional • The cards show 6, 2 and 4 questions • GROUP BY q.id alone is Postgres-only; leave show() alone Doctrine ORM: Deep Dive · Warsaw 2026 · 03
  99. SYMFONYCON WARSAW 2026 04 Caching Do less work, and know

    when the cache is wrong Doctrine ORM: Deep Dive · Warsaw 2026
  100. CACHING · 4.1 Caching layers Four caches · Cache pools

    in Symfony Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  101. Caching layers Topics Metadata cache and query cache Result cache:

    lifetime, ids and invalidation Second-level cache: modes, regions, associations Symfony cache pools per Doctrine cache Measuring the effect in the toolbar Doctrine ORM: Deep Dive · Warsaw 2026 · 04 Hands-on lab Cache a hot query, then break and fix invalidation
  102. Four caches Cache What it stores Status in the docs

    Metadata Parsed entity mapping Recommended in production Query DQL translated to SQL Recommended in production Result Rows returned by a query Optional, per query Second level Entities, collections and queries by region Experimental, extra package since 3.8 Metadata and query cache belong in every production setup. Result and second-level cache are a decision. Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  103. Cache pools in Symfony doctrine: orm: metadata_cache_driver: type: pool pool:

    doctrine.system_cache_pool query_cache_driver: type: pool pool: doctrine.system_cache_pool result_cache_driver: type: pool pool: doctrine.result_cache_pool Doctrine ORM: Deep Dive · Warsaw 2026 · 04 Configuration Each Doctrine cache points to a framework cache pool Pools are defined under framework.cache.pools Development: an in-memory array cache is enough Production: a persistent pool, for example PHP files
  104. CACHING · 4.2 Result and second-level cache Result cache ·

    Second-level cache · Should you cache? Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  105. Result cache Enable, tune, disable // All at once $query->enableResultCache(3600,

    'featured_products'); // Or one setting at a time $query->enableResultCache() ->setResultCacheLifetime(3600) ->setResultCacheId('featured_products'); // Turn it off again $query->disableResultCache(); // Stay enabled, refresh this run $query->expireResultCache(true); Doctrine ORM: Deep Dive · Warsaw 2026 · 04 Handle with care Opt-in per query: nothing is cached unless you enable it Stores the result, not the entities' current state Set an explicit id so you can delete the entry Invalidation is your job: expire by time or delete by id
  106. Result cache or second-level cache? Result cache Second-level cache Stores

    Rows or objects a query returned Entities by id, collections and queries as id lists Switch on Per query: enableResultCache() Invalidation Yours: expire by time, or delete by id The ORM refreshes entries on commit, but cannot see other applications Use it for A known expensive report that may be a bit stale Reference data that is read by id again and again On the entity: #[ORM\Cache] , queries: setCacheable(true) Second-level cache: experimental, separate package since 3.8. Use it sparingly. Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  107. Second-level cache Mapping Configuration #[ORM\Entity] #[ORM\Cache(usage: 'READ_ONLY', region: 'reference_data')] class

    Country { #[ORM\ManyToMany(targetEntity: Language::class)] #[ORM\Cache] private Collection $languages; } doctrine: orm: second_level_cache: region_lifetime: 3600 regions: reference_data: lifetime: 86400 Defaults: usage READ_ONLY, region from the class name. Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  108. Second-level cache: usage modes READ_ONLY Data never changes, no locks

    Insert: the entity is cached after the commit → Reads are served from the cache → Update: the ORM throws an exception NONSTRICT_READ_WRITE Updates allowed, no locks UPDATE runs in the database, the cache still holds the old data → Commit: the new data is written to the cache → Until the commit, readers can see stale data → UPDATE runs in the database → Commit: the entry is evicted, the next read refills the cache READ_WRITE Locks for consistency The entry is locked, readers go to the database Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  109. Should you cache? 1. Measure 2. Pick the level 3.

    Plan invalidation Find the expensive query in the toolbar first. Many slow pages need an index or a join, not a cache. Whole responses and application caches are often simpler than caching inside Doctrine. Decide how stale data is allowed to be, and who clears the entry when data changes. Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  110. Lab: cache a hot query Exercise 5 · 03-result-caching.md 1.

    2. 3. 4. 5. Remove enableResultCache , change a title with dbal:run-sql : it shows at once Restore ->enableResultCache($ttl, OVERVIEW_CACHE_KEY) : the change stays stale Call invalidatePublishedSummariesCache() after the flush in new() and edit() Edit a title in /admin/quizzes : the new title shows at once Try cache:pool:clear doctrine.result_cache_pool as a blunt tool Watch out Verify • The pools exist, but a query must opt in • No query for the overview on the second request • A fixed cache id is needed so invalidation can target it • Tests use an in-memory pool and reset the key in setUp() • The TTL of 300 is a safety net, not the strategy Doctrine ORM: Deep Dive · Warsaw 2026 · 04
  111. SYMFONYCON WARSAW 2026 05 Events Hook into the lifecycle without

    surprises Doctrine ORM: Deep Dive · Warsaw 2026
  112. EVENTS · 5.1 Lifecycle and flush events Entity lifecycle events

    · Flush and other events Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  113. Lifecycle events Topics • Event overview: persist, update, remove, load,

    flush • Lifecycle callbacks vs. listeners vs. entity listeners • Registering listeners as Symfony services • onFlush and the UnitOfWork for advanced cases • Pitfalls: side effects, ordering, performance Doctrine ORM: Deep Dive · Warsaw 2026 · 05 Hands-on lab Fill timestamps and write an audit entry with listeners
  114. Entity lifecycle events Event Triggered by Good to know prePersist

    persist() Generated id not set yet postPersist flush() Generated id is available preUpdate flush(), if data changed Fields only, via setNewValue() postUpdate flush() Changes are in the database preRemove remove() Cascaded removes run first postRemove flush() After the DELETE postLoad Hydration, refresh() Lazy associations not loaded yet Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  115. Flush and other events Event Fires Use for preFlush At

    the start of flush() Last changes before tracking onFlush After changes are computed, before SQL Auditing, advanced logic postFlush After all SQL was executed Side effects like messages onClear When the EntityManager is cleared Resetting your own state loadClassMetadata When mapping data of a class is loaded Changing mapping at runtime onFlush gives access to the UnitOfWork: getScheduledEntityInsertions(), Updates() and Deletions(). Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  116. EVENTS · 5.2 Listening to events Three ways to listen

    · Listeners in Symfony · Pitfalls Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  117. Three ways to listen Way Where it lives Best for

    Lifecycle callback A method on the entity Small logic using only the entity Event listener A service for all entities Cross-cutting concerns Entity listener A service for one entity class Entity logic that needs services Callbacks need #[ORM\HasLifecycleCallbacks] and an attribute such as #[ORM\PreUpdate]. Event subscribers are deprecated in favor of listeners. Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  118. Listeners in Symfony #[AsDoctrineListener(event: Events::postPersist)] final class SearchIndexListener { public

    function postPersist( PostPersistEventArgs $args ): void { $entity = $args->getObject(); // update the index } } Doctrine ORM: Deep Dive · Warsaw 2026 · 05 Registration • AsDoctrineListener for event listeners • AsEntityListener for one entity class • Or tag services with doctrine.event_listener • Listeners are normal services with autowiring
  119. Pitfalls with events No flush inside a listener Side effects

    too early Flushing while Doctrine is flushing leads to recursion and broken state. Sending an email before the commit tells users about data that may be rolled back. Use postFlush or Messenger. preUpdate limits Cost per entity Change fields with setNewValue(); A listener runs for every entity and every batch row. Keep it cheap. associations cannot be changed here. No events with the DBAL Writes through the DBAL connection, bulk DQL statements and raw SQL never fire ORM lifecycle events. Listeners for timestamps or audit entries miss them. Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  120. Lab: audit log with a listener Exercise 6 · 07-completion-audit-log.md

    1. 2. 3. 4. 5. Add QuizAttemptCompletionLog , with no foreign keys so rows survive deletes Write a preUpdate listener: when completedAt changes from null, persist() a log Complete an attempt: the table stays empty, and there is no error Buffer the entries and persist them in postFlush , with a second flush Clear the buffer before the nested flush, or postFlush recurses Watch out Verify • The flush plan is fixed by preUpdate : a persist there is ignored • /admin/audit-log shows one entry, no duplicate on resubmit • Clearing after the nested flush ends in a memory fatal • Both audit log tests in make test pass • The listener is global: check instanceof QuizAttempt Doctrine ORM: Deep Dive · Warsaw 2026 · 05
  121. LOCKING · 6.1 The lost update Concurrency problems · Optimistic

    locking Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  122. Optimistic and pessimistic locking Topics Concurrency problems: lost updates, stale

    reads Optimistic locking with a version field Pessimistic read and write locks in transactions Handling lock exceptions in controllers and workers Doctrine ORM: Deep Dive · Warsaw 2026 · 06 Hands-on lab Reproduce a conflicting edit from two browser tabs, then resolve it
  123. The lost update 1. Both read 2. Anna saves 3.

    Ben saves Anna and Ben open the same product. Stock is 10. She buys two items and stores stock 8. He buys one item and stores stock 9. Anna's change is gone. Nothing failed, yet the data is wrong. Locking makes the conflict visible or prevents it. Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  124. Optimistic locking In the entity In the service class Product

    { #[ORM\Version] #[ORM\Column(type: 'integer')] private int $version; } $product = $em->find(Product::class, $id); try { $em->lock($product, LockMode::OPTIMISTIC, $expectedVersion); $em->flush(); } catch (OptimisticLockException $e) { // reload, merge or ask the user } The entity only declares the version column; Doctrine increments it on every update The service passes the version the user saw; UPDATE only succeeds if it is unchanged Works across requests: keep the version in the form Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  125. Lab: optimistic locking Exercise 7 · 05-optimistic-locking.md 1. 2. 3.

    4. 5. Read Quiz::$version with #[ORM\Version] and the hidden version form field Open /admin/quizzes/{id}/edit for the same quiz in two tabs Save tab 1: the version moves from 1 to 2 Save tab 2: it is rejected with a flash message Read edit() : $entityManager->lock($quiz, LockMode::OPTIMISTIC, $version) Watch out Verify • The flush() check alone cannot catch it: $quiz • SELECT id, version FROM quiz is reloaded per request • A tampered version fails safe, in both directions • Raw SQL bypasses the check; a pessimistic lock would be wrong here Doctrine ORM: Deep Dive · Warsaw 2026 · 06 goes up by 1 per successful edit • testEditingAQuizWithAStaleVersionIsRejectedAsAConf lict passes
  126. LOCKING · 6.2 Pessimistic locking Row locks · Reload under

    a lock · Retries · Skip locked · Which lock to use Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  127. Pessimistic locking $em->wrapInTransaction( function () use ($em, $id) { $product

    = $em->find( Product::class, $id, LockMode::PESSIMISTIC_WRITE ); $product->decreaseStock(1); } ); Doctrine ORM: Deep Dive · Warsaw 2026 · 06 Row locks PESSIMISTIC_WRITE: exclusive lock, others wait to lock or change the row PESSIMISTIC_READ: shared lock, others may read and share it, but not change the row Held until commit or rollback, so keep the transaction short Needs an active transaction
  128. Pessimistic locking in a repository ProductRepository Caller, inside a transaction

    public function findForUpdate(int $id): ?Product { return $this->createQueryBuilder('p') ->andWhere('p.id = :id') ->setParameter('id', $id) ->getQuery() ->setLockMode(LockMode::PESSIMISTIC_WRITE) ->getOneOrNullResult(); } $em->wrapInTransaction( function () use ($repo, $id) { $product = $repo->findForUpdate($id); $product->decreaseStock(1); } ); setLockMode() is on the Query, not the QueryBuilder, and needs an active transaction. Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  129. Reload under a lock $product = $em->find(Product::class, $id); // later:

    the entity may be stale $em->wrapInTransaction( function ($em) use ($product) { $em->refresh( $product, LockMode::PESSIMISTIC_WRITE ); $product->decreaseStock(1); } ); Doctrine ORM: Deep Dive · Warsaw 2026 · 06 Already loaded? An entity loaded earlier may hold stale data Refreshing with a lock mode re-reads the row and locks it Unflushed changes on that entity are overwritten $em->lock() locks the row, but does not reload it
  130. Lock failures and retries Retry the whole transaction for ($try

    = 1; ; ++$try) { $em = $registry->getManager(); try { $em->wrapInTransaction( fn () => $this->decrease($em, $id) ); return; } catch (RetryableException $e) { $registry->resetManager(); if ($try === 3) { throw $e; } } } Retry the whole transaction, never just the failed statement. Doctrine ORM: Deep Dive · Warsaw 2026 · 06 When the lock cannot be had DeadlockException: the database aborted your transaction LockWaitTimeoutException: the wait ran out Both implement RetryableException; a Postgres lock timeout does not wrapInTransaction() closes the EntityManager on failure, so reset it before retrying
  131. Skip locked rows with DBAL Job queue: one row per

    worker $id = $conn->createQueryBuilder() ->select('id') ->from('job') ->where('status = :status') ->setParameter('status', 'new') ->setMaxResults(1) ->forUpdate(ConflictResolutionMode::SKIP_LOCKED) ->executeQuery() ->fetchOne(); SKIP LOCKED Rows locked by others are skipped, not waited for Several workers each get a different row Portable only via the DBAL QueryBuilder: forUpdate() The ORM's setLockMode() has no equivalent; raw SQL works but is platform-specific ConflictResolutionMode has ORDINARY (wait) and SKIP_LOCKED, but no NOWAIT. Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  132. Which lock to use Question Optimistic Pessimistic Lock mode OPTIMISTIC

    PESSIMISTIC_READ / _WRITE Conflicts are Rare Frequent Database locks None Held until commit Spans requests Yes No, one transaction On conflict Exception on flush or lock() Others wait; deadlock or timeout Needs A version column, also for queries A transaction Then Reload, merge or ask the user Retry the whole transaction Doctrine ORM: Deep Dive · Warsaw 2026 · 06
  133. SYMFONYCON WARSAW 2026 07 Batch processing Large data sets without

    running out of memory Doctrine ORM: Deep Dive · Warsaw 2026
  134. BATCH PROCESSING · 7.1 Memory and batches Why batches run

    out of memory · Batch inserts · Large result sets Doctrine ORM: Deep Dive · Warsaw 2026 · 07
  135. Batch inserts, updates and reads Topics • Flush and clear

    in chunks; memory and the identity map • Streaming reads with toIterable() • Bulk DQL and plain DBAL when the ORM is overhead • Splitting work across workers, for example Messenger • Disabling logging and profiling in batch runs Doctrine ORM: Deep Dive · Warsaw 2026 · 07 Hands-on lab Import and reprice many records; compare naive, chunked and DBAL variants
  136. Why batches run out of memory Identity map Growing flushes

    Hydration and profiling The UnitOfWork keeps every managed entity. Nothing is released until you clear or detach it. Each flush checks all managed entities for changes, so the work grows with the count. Building objects is a large part of the cost. In debug mode the profiler keeps every query in memory. Doctrine ORM: Deep Dive · Warsaw 2026 · 07
  137. Batch inserts foreach ($rows as $i => $row) { $em->persist(new

    Product($row['name'])); if (($i + 1) % 100 === 0) { $em->flush(); $em->clear(); } } Flush and clear • Flush every N rows, then clear the identity map • Choose N by measuring; 100 is only a start • Entities you still need must be loaded again after clear() $em->flush(); $em->clear(); Doctrine ORM: Deep Dive · Warsaw 2026 · 07 • IDENTITY ids cost one INSERT per row
  138. Reading large result sets $query = $em->createQuery( 'SELECT p FROM

    App\Entity\Product p' ); toIterable() foreach ($query->toIterable() as $i => $p) { $p->reprice(); • Still needs clear() to free memory if (($i + 1) % 100 === 0) { $em->flush(); $em->clear(); } } Doctrine ORM: Deep Dive · Warsaw 2026 · 07 • Hydrates one row at a time instead of building a full list • Not usable with fetch-joined collections
  139. BATCH PROCESSING · 7.2 Bulk changes and tuning Bulk changes

    without entities · Workers · Measure and tune Doctrine ORM: Deep Dive · Warsaw 2026 · 07
  140. Bulk changes without entities Bulk DQL Plain DBAL UPDATE App\Entity\Product

    p SET p.price = p.price * 1.1 WHERE p.active = true $conn->executeStatement( 'INSERT INTO archive SELECT * FROM product WHERE NOT active' ); One statement, no hydration Skips events and versioning Managed entities become stale Doctrine ORM: Deep Dive · Warsaw 2026 · 07 Full SQL power Ideal for copy and cleanup jobs
  141. Splitting work across workers Partition Messenger Long-running processes Split by

    id range or by chunks of ids. Every worker handles its own slice. Send messages with ids, not entities. The handler loads what it needs and clears when done. Keep handlers idempotent, expect retries, and never reuse a closed EntityManager. Doctrine ORM: Deep Dive · Warsaw 2026 · 07
  142. Measure and tune Step Why Run in prod mode, no

    debug The profiler keeps every query; SQL logging stays on until the logger is muted Print peak memory memory_get_peak_usage() shows whether clear() works Time per 1000 rows Compare chunk sizes with numbers, not guesses Profile hydration If objects dominate the time, switch to DTOs or the DBAL Check the database Indexes and lock waits matter more than PHP at scale Doctrine ORM: Deep Dive · Warsaw 2026 · 07
  143. Lab: import 50,000 rows Exercise 8 · 09-batch-importing.md 1. 2.

    3. 4. Run make db-generate-questions-csv (50,000 rows) Import with --batch-size=0 : memory fatal in UnitOfWork.php Import with --batch-size=200 : a second fatal, in BacktraceDebugDataHolder.php Add --no-debug : 50,000 rows in under a minute Watch out Verify • Two different memory problems, the same message: read the class • SELECT count(*) for loadtest-cat-% shows 50,000 • profiling_collect_backtrace logs every query, and clear() cannot reset that • getReference() survives clear() , managed entities do not Doctrine ORM: Deep Dive · Warsaw 2026 · 07 • Run the cleanup commands afterwards
  144. SYMFONYCON WARSAW 2026 08 Migrations Change the schema safely, repeatably

    and in reverse Doctrine ORM: Deep Dive · Warsaw 2026
  145. MIGRATIONS · 8.1 Writing migrations The workflow · Anatomy of

    a migration · Control flow and hooks Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  146. Doctrine Migrations Topics • Generating and reviewing diffs; up() and

    down() • Transactions, lifecycle hooks and flow control • Data migrations vs. schema migrations • Rollups and keeping history manageable • Deploying with zero-downtime in mind Doctrine ORM: Deep Dive · Warsaw 2026 · 08 Hands-on lab Add a column to a table with data: migrate up, down and up again
  147. The migration workflow Every schema change Change the entity mapping

    doctrine:migrations:diff Review and edit the generated SQL doctrine:migrations:migrate Commit the migration with the code Doctrine ORM: Deep Dive · Warsaw 2026 · 08 Also useful doctrine:migrations:status doctrine:schema:validate in CI schema:update --force is for prototypes only
  148. Anatomy of a migration final class Version20260601120000 extends AbstractMigration {

    public function getDescription(): string { return 'Add SKU to product'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE product ADD sku VARCHAR(32) DEFAULT NULL'); } } Doctrine ORM: Deep Dive · Warsaw 2026 · 08 Parts • Class name is the version, with a timestamp • up() applies, down() reverts • addSql() queues statements
  149. Control flow and hooks Method Effect warnIf($condition, $message) Prints a

    warning and continues abortIf($condition, $message) Stops and rolls back skipIf($condition, $message) Skips this migration throwIrreversibleMigrationException() Marks a down() as impossible preUp, postUp, preDown, postDown Hooks around the schema changes isTransactional() Return false to run without a transaction Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  150. MIGRATIONS · 8.2 Data and deployment Data migrations · Deploying

    without downtime · Housekeeping Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  151. Data migrations Separate from schema SQL, not entities Put data

    changes in their own migration, so a failure is easy to understand. Entities change over time and old migrations would break. Use SQL or the connection. Big tables in chunks Try on a copy One giant UPDATE holds locks. Work in batches, or run it as a command outside the deploy. Run against production-like data and check duration and results first. Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  152. Deploying without downtime 1. Expand 2. Migrate 3. Contract Add

    the new column or table, nullable. The old code keeps working. Deploy code that writes both versions, and backfill existing rows. In a later release, remove the old column and add the constraints. A rename is an expand and a contract, never a single ALTER during a live deploy. Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  153. Example: renaming a column 1. Expand · release 1 2.

    Migrate · release 2 3. Contract · release 3 ALTER TABLE quiz ADD name VARCHAR(150) DEFAULT NULL; // entity: write both $this->title = $v; $this->name = $v; -- backfill, in batches UPDATE quiz SET name = title WHERE name IS NULL AND id <= :batchEnd; ALTER TABLE quiz ALTER name SET NOT NULL; ALTER TABLE quiz DROP title; Old code never reads name, so nothing breaks. New writes fill both columns. Then switch reads to name. No code reads title any more: tighten the constraint, drop the column. Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  154. Housekeeping Shell Rollup Squash old migrations into one starting point

    after a release. $ bin/console doctrine:migrations:dump-schema # delete the old migration files, keep the dumped one $ bin/console doctrine:migrations:rollup config/packages/doctrine.yaml Foreign tables Keep Doctrine away from tables it does not own. doctrine: dbal: schema_filter: ~^(?!legacy_|audit_)~ CI job CI check Fail the build when mapping and database differ. Doctrine ORM: Deep Dive · Warsaw 2026 · 08 $ bin/console doctrine:migrations:migrate -n $ bin/console doctrine:schema:validate # non-zero exit: mapping invalid or schema out of sync
  155. Lab: change a live table Tasks Add a nullable column

    to an entity [entity] Generate the diff and read the SQL Write a separate data migration that fills it Migrate up, down and up again Make the column required in a third step Doctrine ORM: Deep Dive · Warsaw 2026 · 08 Goal You can ship a schema change in safe, reversible steps.
  156. Lab: index a time-range query Exercise 9 · 08-time-range-indexing.md 1.

    2. 3. 4. 5. Run make db-generate-attempts (20,000 attempts), then ANALYZE quiz_attempt Roll back one migration with doctrine:migrations:execute --down Run EXPLAIN ANALYZE for the activity report query in psql Add #[ORM\Index] on user_id, completed_at , generate and migrate Compare the plan: one Bitmap Index Scan instead of a filter Watch out Verify • Equality columns first, range column last • dbal:run-sql cannot show EXPLAIN output, use psql • The Index Cond covers both columns, no "Rows Removed by Filter" • A manual CREATE INDEX is invisible to the migrations table • doctrine:schema:validate is clean Doctrine ORM: Deep Dive · Warsaw 2026 · 08
  157. SYMFONYCON WARSAW 2026 09 Testing Fast, isolated tests against a

    real database Doctrine ORM: Deep Dive · Warsaw 2026
  158. TESTING · 9.1 Test setup What to test where ·

    A test database · Isolating tests with DAMA · What DAMA hides · SQLite for tests? Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  159. Testing Doctrine code Topics What to unit test and what

    needs a database Test database setup and schema creation Transaction rollback per test with DAMA test bundle Test data with Foundry factories Testing repositories, listeners and migrations Doctrine ORM: Deep Dive · Warsaw 2026 · 09 Hands-on lab Write a repository test and a listener test
  160. What to test where Level Database Typical targets Unit No

    Entity behavior, value objects, services Integration Yes Repositories, queries, mapping Functional Yes, plus kernel Controllers, listeners, commands Do not mock the EntityManager to test a query. A mock cannot tell you if the query is right. Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  161. A test database # .env.test DATABASE_URL="postgresql://app:secret@db/app_test" # once, and after

    mapping changes bin/console --env=test doctrine:database:create bin/console --env=test doctrine:migrations:migrate -n Doctrine ORM: Deep Dive · Warsaw 2026 · 09 Setup rules Same database engine as production Build the schema from migrations, so they get tested too Give parallel test runs their own database name
  162. Isolating tests with DAMA <!-- phpunit.xml.dist --> <extensions> <bootstrap class="DAMA\DoctrineTestBundle\

    PHPUnit\PHPUnitExtension"/> </extensions> Doctrine ORM: Deep Dive · Warsaw 2026 · 09 dama/doctrine-test-bundle Wraps every test in a transaction and rolls it back Fast: no schema rebuild between tests Enable the bundle for the test environment Never really commits: caveats on the next slide
  163. DAMA: what it hides Strategy Speed Real commits Watch out

    for DAMA rollback Fastest No, savepoints only Locking, deferred constraints, other connections Truncate or reload per test Medium Yes Reloading fixtures costs time on big data Recreate schema per test Slowest Yes Fully isolated, rarely worth the time Downsides of DAMA Commits become savepoint releases: nothing is ever really committed Other processes (browser tests, workers) cannot see the test data Auto-increment IDs are not reset, so never assume id 1 Static metadata and query caches are optional, but share state between tests Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  164. SQLite in memory for tests? Pros Fast: no server round

    trips, the database lives in memory No infrastructure: nothing to start locally or in CI A clean database per process, also with parallel runs Fine for mapping and hydration checks and simple queries Cons Different SQL dialect, types and functions than production A query can pass here and fail on production, or the reverse No row locks, so pessimistic locking cannot be tested Migrations and engine features (JSON, partial indexes) are not tested Green tests give false confidence Speed is rarely the bottleneck: with DAMA, a real database is already fast. Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  165. TESTING · 9.2 Test data and test types Foundry ·

    A repository test · Listeners, locks and migrations Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  166. Test data with Foundry final class ProductFactory extends PersistentObjectFactory {

    public static function class(): string { return Product::class; } protected function defaults(): array { return ['name' => self::faker()->word()]; } } Doctrine ORM: Deep Dive · Warsaw 2026 · 09 zenstruck/foundry • One factory per entity with sensible defaults • createOne() and createMany() persist for you • Override only what the test cares about
  167. A repository test final class ProductRepositoryTest extends KernelTestCase { use

    Factories; public function testFindsFeatured(): void { ProductFactory::createOne(['featured' => true]); ProductFactory::createOne(['featured' => false]); $repo = self::getContainer() ->get(ProductRepository::class); self::assertCount(1, $repo->findFeatured()); } } Doctrine ORM: Deep Dive · Warsaw 2026 · 09 Arrange, act, assert Create only the rows that matter Call the repository method Assert on the returned entities
  168. Listeners, locks and migrations Listeners Locks Migrations Test them through

    the ORM: persist, flush, then assert on the result. Optimistic: simulate the conflict on one connection. Pessimistic: two real connections, outside the rollback wrapper. In CI: migrate an empty database, then validate the schema. Doctrine ORM: Deep Dive · Warsaw 2026 · 09
  169. Lab: test isolation and factories Exercise 10 · 10-test-isolation-and-factories.md 1.

    2. 3. 4. 5. Read the factories in tests/Factory , e.g. withOptions() with afterInstantiate() Rebuild one test by hand and compare the diff Disable DAMA in config/bundles.php and recreate the test database Run RegistrationControllerTest twice: the second run fails on duplicate emails Enable enable_auto_refresh_with_lazy_objects , read the error, undo both changes Watch out Verify • Use PersistentObjectFactory • make test passes twice and with -- --order-by=random : the proxy factory is deprecated in Foundry 2.7 • Pure unit tests stay a plain TestCase • QuestionGraphTest is hand-built on purpose Doctrine ORM: Deep Dive · Warsaw 2026 · 09 • The user table in the test database is empty
  170. Key takeaways Block Remember Architecture EntityManager, UnitOfWork, and the DBAL

    below them Mapping, querying Use the right tool per use case; DTOs for reads Debugging Check the toolbar on every page you build Caching Measure first; plan invalidation Events Small listeners; no flush inside them; side effects after commit Locking Optimistic across requests, pessimistic when short Batch processing Flush and clear in chunks; stream reads; DBAL for bulk Migrations Review diffs; expand, migrate, contract Testing Real database, rollback per test, factories Doctrine ORM: Deep Dive · Warsaw 2026
  171. SYMFONYCON WARSAW 2026 Resources Example project: github.com/BibisCodingPalace/doctrine-workshop-warsaw ORM: doctrine-project.org/projects/orm.html DBAL:

    doctrine-project.org/projects/dbal.html Migrations: doctrine-project.org/projects/migrations.html Symfony and Doctrine: symfony.com/doc/current/doctrine.html Earlier version of this talk: speakerdeck.com/dbrumann/doctrine-orm-deep-dive Doctrine ORM: Deep Dive · Warsaw 2026 · Questions and feedback: [contact]

More Decks by Denis Brumann

Other Decks in Programming