Chapter 06 · Tactics · DDD Building Blocks

DDD Building Blocks

Entities, Value Objects, aggregates, repositories, and domain events. For each building block, the chapter shows which problem it solves and what it looks like in PHP 8.4 and Symfony 8.

Author M. Katuščák
Reading time ≈ 19 min
Difficulty intermediate
Published · Updated ·
In this chapter

06.01 Bounded Contexts#

The word “customer” means something different in marketing than in billing. A team that merges both meanings into one class ends up with a model full of fields, half of which mean nothing in any given use. A Bounded Context is an explicitly delimited area inside which one consistent model and one vocabulary apply [1]. Different contexts therefore have deliberately different models. The topic is strategic: the overall frame is given in What Is Domain-Driven Design, and the relationships and integration between contexts are covered in Bounded Context and Context Mapping. The Case Study shows a real system split into five contexts. Here, a context serves only as the boundary inside which the tactical building blocks live.

FIG. 06.1-A Bounded Contexts

06.02 Ubiquitous Language#

When the code talks about Customer and the product team about a “user,” every conversation about requirements starts with a translation. Meanings get lost in it. Ubiquitous Language is a single vocabulary that developers agree on with domain experts and that then applies consistently in code, documentation, and everyday conversation [2]. Why the language emerges and how it is built is described in What Is Domain-Driven Design. Where one language ends and another begins is set by the Bounded Context boundary; the relationships between contexts are covered in Bounded Context and Context Mapping.

FIG. 06.2-A Ubiquitous Language

06.03 Entities#

What tells two users with the same name and email apart is identity. An entity is a domain object that carries its own identifier and keeps it for its whole life. In the DDD Reference, Evans writes that such an object is defined by a thread of continuity and identity, not by its attributes [3]. The name, address, and email can all change – the identity stays.

php src/UserManagement/Domain/Model/User.php (without persistence)
1<?php2 3declare(strict_types=1);4 5namespace App\UserManagement\Domain\Model;6 7use App\UserManagement\Domain\ValueObject\Email;8use App\UserManagement\Domain\ValueObject\UserId;9 10class User11{12    public readonly \DateTimeImmutable $createdAt;13 14    public function __construct(15        // The identity is a public readonly property, just like in the canonical16        // User from the Implementation in Symfony chapter. The rest of the book17        // reads it as `$user->id`, not through a getter.18        public readonly UserId $id,19        private string $name,20        private Email $email,21    ) {22        $this->createdAt = new \DateTimeImmutable();23    }24 25    public function name(): string26    {27        return $this->name;28    }29 30    public function email(): Email31    {32        return $this->email;33    }34 35    public function changeName(string $name): void36    {37        $this->name = $name;38    }39 40    public function changeEmail(Email $email): void41    {42        $this->email = $email;43    }44 45    public function equals(self $other): bool46    {47        return $this->id->equals($other->id);48    }49}

Entity equality

Two entities are the same exactly when they have the same ID. That is why equals() compares identifiers only. The == operator does not fit, because it compares all properties at once. The same user loaded twice from the database passes, but as soon as one of the instances changes its email, == marks it as a different entity, even though the identity has not changed. The === operator, in turn, compares instances in memory. Within one EntityManager, Doctrine returns the same instance for the same ID thanks to the Identity Map. An entity obtained twice independently (once by deserializing a message, once from the database, or reloaded after $em->clear()) exists as two instances, though, and === returns false even when both are the same domain entity.

Where identity comes from

The User example receives its UserId through the constructor and does not care where it came from. In Implementing Domain-Driven Design (2013), Vernon lists four ways an identity can come into being. The user provides the value (User Provides Identity), the application generates it (Application Generates Identity), the persistence mechanism generates it (Persistence Mechanism Generates Identity), or another Bounded Context assigns it (Another Bounded Context Assigns Identity) [4].

The book chooses the second one. An aggregate that gets its identifier only from the database does not have one when it is created. It therefore cannot record an event about its own creation, and no other aggregate can refer to it. Matthias Noback reaches the same conclusion and recommends creating the ID before the object comes into existence [5]. Identifiers in this book are therefore created with Uuid::v7() from the symfony/uid package. The documentation recommends this version over versions 1 and 6 for its better entropy and stricter chronological ordering [6].

php src/UserManagement/Domain/ValueObject/UserId.php (basic form)
1<?php2 3declare(strict_types=1);4 5namespace App\UserManagement\Domain\ValueObject;6 7use Symfony\Component\Uid\Uuid;8 9final readonly class UserId10{11    public function __construct(12        public string $value,13    ) {14        if (!Uuid::isValid($value)) {15            throw new \InvalidArgumentException('UserId must be a valid UUID');16        }17    }18 19    public static function generate(): self20    {21        return new self((string) Uuid::v7());22    }23 24    public static function fromString(string $value): self25    {26        return new self($value);27    }28 29    // Doctrine converts the identity to a string on every persist().30    // Without __toString(), saving fails right away – see the implementation chapter.31    public function __toString(): string32    {33        return $this->value;34    }35 36    public function equals(self $other): bool37    {38        return $this->value === $other->value;39    }40}

The other identifiers in the book have the same shape and differ only in name and error message. Because they appear throughout, they are collected here:

php src/Ordering/Domain/ValueObject/OrderId.php + CustomerId.php + ProductId.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\ValueObject;6 7use Symfony\Component\Uid\Uuid;8 9// Identity of the canonical Order aggregate. Doctrine converts it to a string10// on every persist(), so __toString() is not cosmetic here - without it,11// saving ends with the message "could not be converted to string".12final readonly class OrderId13{14    public function __construct(public string $value)15    {16        if (!Uuid::isValid($value)) {17            throw new \InvalidArgumentException('OrderId must be a valid UUID');18        }19    }20 21    public static function generate(): self { return new self((string) Uuid::v7()); }22 23    public static function fromString(string $value): self { return new self($value); }24 25    public function equals(self $other): bool { return $this->value === $other->value; }26 27    public function __toString(): string { return $this->value; }28}29 30final readonly class CustomerId31{32    public function __construct(public string $value)33    {34        if (!Uuid::isValid($value)) {35            throw new \InvalidArgumentException('CustomerId must be a valid UUID');36        }37    }38 39    public static function generate(): self { return new self((string) Uuid::v7()); }40 41    public static function fromString(string $value): self { return new self($value); }42 43    public function equals(self $other): bool { return $this->value === $other->value; }44 45    public function __toString(): string { return $this->value; }46}47 48final readonly class ProductId49{50    public function __construct(public string $value)51    {52        if (!Uuid::isValid($value)) {53            throw new \InvalidArgumentException('ProductId must be a valid UUID');54        }55    }56 57    public static function generate(): self { return new self((string) Uuid::v7()); }58 59    public static function fromString(string $value): self { return new self($value); }60 61    public function equals(self $other): bool { return $this->value === $other->value; }62 63    public function __toString(): string { return $this->value; }64}

The repetition is deliberate. A shared parent would save lines, but it would weaken type checking. An equals(self $other) method inherited from the parent accepts any subclass, so comparing a CustomerId with a ProductId passes without an error. The same holds for every signature that accepts the parent. Preventing exactly that is what typed identifiers are for. The Aggregate Design chapter also shows OrderId written out in full.

A natural identifier is acceptable too. Evans explicitly allows both options: the identity can come from outside, or it is an artificial value the system creates for itself [3]. Even a national ID number, an ISBN, or a company registration number is less stable than it looks, though: they change, and they are sometimes assigned incorrectly or issued twice. Whoever uses one as an aggregate's primary identity inherits all of its exceptions. The safer route is to keep an artificial ID and carry the natural key as an ordinary attribute with a unique index.

06.04 Value Objects#

Two emails with the same text are not “two addresses” but one value. A value object has no identity; only its attributes matter. Because it has no identity, nothing prevents keeping it immutable, and Evans recommends doing so [3]. It is compared by value, not by reference. There is a practical argument for value objects too. Scattered primitives such as string $email, int $priceInCents, and string $currency are a code smell Fowler named Primitive Obsession [7]; before-and-after examples are in Anti-Patterns and Common Mistakes.

php src/UserManagement/Domain/ValueObject/Email.php (basic form)
1<?php2 3declare(strict_types=1);4 5namespace App\UserManagement\Domain\ValueObject;6 7final readonly class Email8{9    public function __construct(10        public string $value,11    ) {12        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {13            throw new \InvalidArgumentException('Invalid email address');14        }15    }16 17    public static function fromUserInput(string $raw): self18    {19        // Input normalization (lowercase, trim) belongs here, not in the constructor.20        return new self(mb_strtolower(trim($raw)));21    }22 23    public function equals(self $other): bool24    {25        return $this->value === $other->value;26    }27 28    public function __toString(): string29    {30        return $this->value;31    }32}

Email holds a single string as a public readonly property; a getter would only add noise. The constructor guards the format, and the named factory fromUserInput() normalizes input from forms. The class has no ID and no setters, and two emails are equal exactly when they hold the same value. The class is final readonly, so nobody can extend it or change it after creation.

Money and Currency

The second value object the book keeps coming back to combines several values. Money joins an amount and a currency into a concept that cannot be split apart.

php src/SharedKernel/Domain/Money.php + Currency.php
1<?php2 3declare(strict_types=1);4 5// Money is used by Ordering, Billing, and Pricing – hence the Shared Kernel,6// just like AggregateRoot, not the domain folder of a single context.7namespace App\SharedKernel\Domain;8 9enum Currency: string10{11    case CZK = 'CZK';12    case EUR = 'EUR';13    case USD = 'USD';14}15 16final readonly class Money17{18    public function __construct(19        public int $amountInCents,20        public Currency $currency,21    ) {22        if ($amountInCents < 0) {23            throw new \InvalidArgumentException('Money cannot be negative');24        }25    }26 27    public static function zero(Currency $currency): self28    {29        return new self(0, $currency);30    }31 32    public function add(self $other): self33    {34        if ($this->currency !== $other->currency) {35            // A deliberate shortcut: in the Shared Kernel, a named exception would36            // mean another shared type. Inside a context, a named class belongs here.37            throw new \DomainException(38                "Cannot add {$this->currency->value} and {$other->currency->value}"39            );40        }41 42        return new self($this->amountInCents + $other->amountInCents, $this->currency);43    }44 45    public function subtract(self $other): self46    {47        if ($this->currency !== $other->currency) {48            // The same shortcut as in add().49            throw new \DomainException(50                "Cannot subtract {$other->currency->value} from {$this->currency->value}"51            );52        }53 54        return new self($this->amountInCents - $other->amountInCents, $this->currency);55    }56 57    public function multiply(int $factor): self58    {59        return new self($this->amountInCents * $factor, $this->currency);60    }61 62    /** Percentage share. Rates are whole percent; division rounds up. */63    public function percentage(int $percent): self64    {65        return new self(intdiv($this->amountInCents * $percent + 99, 100), $this->currency);66    }67 68    public function equals(self $other): bool69    {70        return $this->amountInCents === $other->amountInCents71            && $this->currency === $other->currency;72    }73}

The amount is an integer in the currency's smallest units (cents, or hellers for CZK). A float would bring rounding errors into money, and they would surface only on the invoice. The currency is held by a string-backed enum, so mixing up 'czk' and 'CZK' is ruled out. Adding two different currencies ends with an exception. That is a domain rule, not a caller's mistake. Subtracting below zero ends with the constructor's exception; a context that needs negative amounts (credit notes) introduces a type of its own. As soon as several contexts need the same concept, Money belongs in the Shared Kernel (this variant is shown in Bounded Context and Context Mapping).

Validation: which exception where

The book distinguishes two levels of validation. A violation of a value's format (an invalid email, a negative amount, a string that is not a UUID) is reported by the value object's constructor with an \InvalidArgumentException. Such a violation is a programmer error or invalid input that the input layer should have caught already. A violation of a business rule (confirming an empty order, paying for an unconfirmed order) is reported by the aggregate with a domain exception extending \DomainException, typically a named class such as InvalidOrderStateTransitionException. The exception hierarchy across layers is covered in Implementation in Symfony 8.

Both rules rest on one assumption: an object must never be in an invalid state, not even for a moment. Vladimir Khorikov calls this the always-valid domain model [10]. It is a choice. The opposite approach moves validation into the input layer and leaves the domain object “dumb.” The book keeps the first variant, because only then is the constructor a guarantee of validity.

06.05 Aggregates#

An order has items, a delivery address, a status, and a total amount. Changing an item requires recalculating the amount; a cancellation requires a status check. When no single place guards these rules, they scatter across services. An aggregate is a group of objects that change as one unit and share one invariant boundary [3]. Access to the aggregate goes exclusively through its root, the Aggregate Root. Equating this boundary with the transaction boundary is Evans's recommendation, not part of the definition. Inside the aggregate, rules are enforced synchronously; across the boundary, changes propagate asynchronously. The rule of thumb “one aggregate per transaction” is derived from this in Aggregate Design. A badly chosen size is among the most common mistakes in DDD; oversized “God Aggregates” are covered in Anti-Patterns and Common Mistakes.

php src/Ordering/Domain/Model/Order.php (without persistence)
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Model;6 7// Both exceptions are listed in the Implementation in Symfony 8 chapter (10.12);8// here, their names and named factories are enough.9use App\Ordering\Domain\Exception\EmptyOrderException;10use App\Ordering\Domain\Exception\InvalidOrderStateTransitionException;11use App\Ordering\Domain\ValueObject\CustomerId;12use App\SharedKernel\Domain\Money;13use App\Ordering\Domain\ValueObject\OrderId;14use App\Ordering\Domain\ValueObject\ProductId;15use App\Ordering\Domain\ValueObject\OrderStatus;16 17final class Order18{19    /** @var list<OrderItem> */20    private array $items = [];21 22    private OrderStatus $status;23    private readonly \DateTimeImmutable $createdAt;24 25    private function __construct(26        // The identity and the owner are public readonly properties, just like27        // in the canonical aggregate from the Aggregate Design chapter. The rest28        // of the book reads them as `$order->id`, not through a getter.29        public readonly OrderId $id,30        public readonly CustomerId $customerId,31    ) {32        $this->status = OrderStatus::Draft;33        $this->createdAt = new \DateTimeImmutable();34    }35 36    public static function place(OrderId $id, CustomerId $customerId): self37    {38        return new self($id, $customerId);39    }40 41    public function addItem(ProductId $productId, int $quantity, Money $unitPrice): void42    {43        if ($this->status !== OrderStatus::Draft) {44            throw InvalidOrderStateTransitionException::notAllowedInState(45                'addItem',46                $this->status->value,47            );48        }49 50        $this->items[] = new OrderItem($productId, $quantity, $unitPrice);51    }52 53    public function removeItem(ProductId $productId): void54    {55        if ($this->status !== OrderStatus::Draft) {56            throw InvalidOrderStateTransitionException::notAllowedInState(57                'removeItem',58                $this->status->value,59            );60        }61 62        $this->items = array_values(array_filter(63            $this->items,64            static fn (OrderItem $item): bool => !$item->productId->equals($productId),65        ));66    }67 68    public function confirm(): void69    {70        if ($this->status !== OrderStatus::Draft) {71            throw InvalidOrderStateTransitionException::cannotTransition(72                $this->status->value,73                OrderStatus::Confirmed->value,74            );75        }76 77        if ($this->items === []) {78            throw EmptyOrderException::cannotConfirm();79        }80 81        $this->status = OrderStatus::Confirmed;82    }83 84    // The reason and time of the cancellation are carried by the OrderCancelled85    // event (see Aggregate Design); this event-free form only accepts them.86    public function cancel(string $reason, \DateTimeImmutable $when): void87    {88        // A cancellation cannot undo a shipped or delivered parcel; a paid order it can.89        if (in_array($this->status, [OrderStatus::Shipped, OrderStatus::Delivered], true)) {90            throw InvalidOrderStateTransitionException::cannotTransition(91                $this->status->value,92                OrderStatus::Cancelled->value,93            );94        }95 96        $this->status = OrderStatus::Cancelled;97    }98 99    public function totalAmount(): Money100    {101        if ($this->items === []) {102            throw EmptyOrderException::hasNoItems();103        }104 105        $total = $this->items[0]->unitPrice->multiply($this->items[0]->quantity);106 107        foreach (array_slice($this->items, 1) as $item) {108            $total = $total->add($item->unitPrice->multiply($item->quantity));109        }110 111        return $total;112    }113 114    /** @return list<OrderItem> */115    public function items(): array116    {117        return $this->items;118    }119 120    public function itemCount(): int121    {122        return count($this->items);123    }124 125    // The basic form with a getter. Since PHP 8.4, it is replaced by asymmetric126    // visibility public private(set); see the Aggregate Design chapter.127    public function status(): OrderStatus128    {129        return $this->status;130    }131 132    public function isConfirmed(): bool133    {134        return $this->status === OrderStatus::Confirmed;135    }136 137    public function createdAt(): \DateTimeImmutable138    {139        return $this->createdAt;140    }141}
php src/Ordering/Domain/Model/OrderItem.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Model;6 7use App\SharedKernel\Domain\Money;8use App\Ordering\Domain\ValueObject\ProductId;9 10class OrderItem11{12    // Public readonly properties, not getters - just like the canonical13    // OrderItem in the Aggregate Design chapter. The rest of the book reads them directly.14    public function __construct(15        public readonly ProductId $productId,16        public readonly int $quantity,17        public readonly Money $unitPrice,18    ) {19        if ($quantity <= 0) {20            throw new \InvalidArgumentException('Quantity must be positive');21        }22    }23}

Order is the aggregate root and holds a collection of OrderItem. The constructor is private and an instance comes from the named factory Order::place(), so nobody can create an order without a customer and without an initial status. Outside calls go exclusively through methods on Order; nobody instantiates or modifies an OrderItem from outside. Every violated rule is reported by a named exception – InvalidOrderStateTransitionException for a disallowed status transition, EmptyOrderException for an empty order. The caller can then decide by type, not by the message text. Both classes, together with OrderNotFoundException from the repository below, are listed in Implementation in Symfony 8; they extend \DomainException, and a named factory carries the error message. The totalAmount() calculation takes the currency from the items. The sum starts with the first item, and Money::add() throws an exception on a mismatch. An order that mixes two currencies therefore does not slip through silently. The aggregate does not record events yet. The AggregateRoot parent and the record() calls are added in the lifecycle section. OrderItem is deliberately simplified here to an immutable record without a reference back to the order; inside the aggregate, the product is enough to identify it. The full version is in Aggregate Design, including the increaseQuantity() method for the “one item per product” invariant.

This form of Order has no persistence: the items live in a plain array, and the class carries not a single Doctrine attribute. The model can be read without knowing the ORM. The version to copy into your project is the one from Aggregate Design. It adds further status transitions (markPaid(), ship()), a Collection instead of an array, the mapping, and an OrderItem with a reference back to the order. Without that reference, Doctrine would have nothing to write into the foreign key.

06.06 Repositories#

The domain layer should not know whether an aggregate lives in PostgreSQL, MongoDB, or memory. The repository keeps the domain ignorant of it: to the domain, it looks like an in-memory collection of aggregates, while the actual storage is handled by an implementation in the infrastructure layer. The pattern comes from the Patterns of Enterprise Application Architecture catalog. Edward Hieatt and Rob Mee describe it there as a mediator between the domain and the data mapping that presents itself as a collection [11].

php src/Ordering/Domain/Repository/OrderRepository.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Repository;6 7use App\Ordering\Domain\Exception\OrderNotFoundException;8use App\Ordering\Domain\Model\Order;9use App\Ordering\Domain\ValueObject\OrderId;10 11interface OrderRepository12{13    public function save(Order $order): void;14 15    /** @throws OrderNotFoundException when the order does not exist */16    public function get(OrderId $id): Order;17}

OrderRepository is deliberately narrow: save an aggregate and load it by identity. A missing order is the caller's error, not an empty result, which is why get() returns Order and throws an exception instead of returning null. The infrastructure chooses the implementation – most often Doctrine ORM, but an in-memory variant for tests works just as well. The Doctrine variant is worked out in Implementation in Symfony 8.

Three rules separate a repository from an ordinary service class over a database:

  1. One repository per aggregate root, not per entity. OrderItem has no repository of its own; it is loaded and saved as part of the order.
  2. The interface returns assembled aggregates, not rows or associative arrays. This is what sets a repository apart from a DAO, which speaks in terms of tables and offers CRUD over them.
  3. Queries for screens, such as “all orders of a customer,” do not belong here. They are served by a read model, covered in CQRS.

The save() method knowingly departs from the original idea of a repository as a collection. Vernon distinguishes two forms. A collection-oriented repository behaves like a collection (add(), remove()) and relies on the persistence mechanism to track changes itself. The persistence-oriented variant with a save() method fits where the storage does not track changes [4]. Doctrine does track changes, so the first form would hold up. An explicit save() is still more readable: the code shows where the write happens.

06.07 Domain Services#

Some rules belong to neither a single aggregate nor a single value object. They coordinate several objects or capture a process without an owner. Such logic goes into a domain service: it holds no state, has no lifecycle, and works with the entities and value objects it receives.

php src/Ordering/Domain/Service/ShippingFeeService.php + Model/Customer.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Service;6 7use App\Ordering\Domain\Model\Customer;8use App\Ordering\Domain\Model\Order;9use App\SharedKernel\Domain\Currency;10use App\SharedKernel\Domain\Money;11 12final class ShippingFeeService13{14    // Order lines are counted, not individual pieces of goods.15    private const int FREE_SHIPPING_FROM_LINES = 5;16    private const int FLAT_FEE_CENTS = 99_00;17 18    public function feeFor(Order $order, Customer $customer): Money19    {20        $freeShipping = $customer->isVip()21            || count($order->items()) >= self::FREE_SHIPPING_FROM_LINES;22 23        return $freeShipping24            ? Money::zero(Currency::CZK)25            : new Money(self::FLAT_FEE_CENTS, Currency::CZK);26    }27}28 29// --- src/Ordering/Domain/Model/Customer.php ---30namespace App\Ordering\Domain\Model;31 32use App\Ordering\Domain\ValueObject\CustomerId;33 34// An illustrative excerpt: the book does not develop the Customer aggregate further;35// the service only needs the loyalty status. A real model would derive it from purchase history.36final class Customer37{38    public function __construct(39        public readonly CustomerId $id,40        private bool $vip = false,41    ) {}42 43    public function isVip(): bool44    {45        return $this->vip;46    }47}

The rule “free shipping for VIP customers and large orders” reads data from two aggregates: Customer and Order. It belongs to neither of them – Customer knows nothing about shipping fees, and Order does not know the customer's loyalty status. ShippingFeeService therefore brings both pieces of knowledge together in one place, with no state and no dependency on a repository or database.

Evans describes a service as an operation the model offers through a standalone interface. The example does not turn it into a PHP interface, because there is a single implementation, and a premature abstraction would only add another file. If a second way of calculating appears, or a test needs to replace the service, a ShippingFeeCalculator interface can be added at any time.

06.08 Domain Events#

“The order was confirmed.” “The payment was received.” A domain event is an immutable record of something that happened in the domain and that domain experts care about. Evans adds that an event usually carries a timestamp and the identity of the entities involved [3]. The name is therefore always in the past tense – it describes a finished fact, not a command.

php src/Ordering/Domain/Event/OrderPlaced.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Event;6 7use App\Ordering\Domain\ValueObject\CustomerId;8use App\Ordering\Domain\ValueObject\OrderId;9 10final readonly class OrderPlaced11{12    public \DateTimeImmutable $occurredAt;13 14    public function __construct(15        public OrderId $orderId,16        public CustomerId $customerId,17    ) {18        $this->occurredAt = new \DateTimeImmutable();19    }20}

OrderPlaced carries three pieces of information: which order it concerns, which customer, and when the event occurred. The properties are public and readonly, because an event is an immutable record and its recipients only read it.

How much data belongs in an event is a decision, not a rule. A thin event carries identifiers, and the recipient fetches the rest itself; a fat one ships the whole state, so the recipient has nothing left to ask. Fowler named the second form Event-Carried State Transfer and lists it alongside plain notification, Event Sourcing, and CQRS as one of four variants of event-driven architecture [12]. Inside a single context, the thin variant shown by OrderPlaced works well: the recipient has access to the aggregate, and duplicated data would drift apart sooner or later.

The context boundary divides events into domain events and integration events. A domain event speaks the language of Ordering and stays inside. An integration event is a contract for other contexts and changes only as fast as its recipients can tolerate [13]. Sending OrderPlaced outside therefore means publishing the internal model, with everything that follows from it. Translation into a stable contract is handled by Published Language. Reliable delivery and idempotency on the recipient's side are covered in Outbox Pattern, because Messenger delivers at-least-once.

Domain Events form the basis of two architectural techniques: separating reads and writes in CQRS and storing state as a sequence of events in Event Sourcing.

06.09 Aggregates and domain events: the lifecycle#

An event reaches its recipients in two steps. The aggregate records it at the moment the change happens – inside a domain method. The application layer publishes it only after the change has been saved. Between the two steps, the events are held by the aggregate root's base class:

php src/SharedKernel/Domain/AggregateRoot.php (basic form)
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain;6 7abstract class AggregateRoot8{9    /** @var list<object> */10    private array $domainEvents = [];11 12    final protected function record(object $event): void13    {14        $this->domainEvents[] = $event;15    }16 17    /** @return list<object> */18    final public function releaseEvents(): array19    {20        $events = $this->domainEvents;21        $this->domainEvents = [];22 23        return $events;24    }25}

The Order aggregate from the aggregates section extends this class. The excerpt shows its place(), addItem(), and confirm() with the record() calls added:

php src/Ordering/Domain/Model/Order.php (excerpt)
1final class Order extends AggregateRoot2{3    // ... properties and methods from section 06.05 ...4 5    public static function place(OrderId $id, CustomerId $customerId): self6    {7        $order = new self($id, $customerId);8        $order->record(new OrderPlaced($id, $customerId));9 10        return $order;11    }12 13    public function addItem(ProductId $productId, int $quantity, Money $unitPrice): void14    {15        // ... status check from section 06.05 ...16        $this->items[] = new OrderItem($productId, $quantity, $unitPrice);17        $this->record(new OrderItemAdded($this->id, $productId, $quantity));18    }19 20    public function confirm(): void21    {22        if ($this->status !== OrderStatus::Draft) {23            throw InvalidOrderStateTransitionException::cannotTransition(24                $this->status->value,25                OrderStatus::Confirmed->value,26            );27        }28 29        if ($this->items === []) {30            throw EmptyOrderException::cannotConfirm();31        }32 33        $this->status = OrderStatus::Confirmed;34        $this->record(new OrderConfirmed($this->id, $this->customerId, new \DateTimeImmutable()));35    }36}

OrderItemAdded and OrderConfirmed are counterparts of OrderPlaced from the previous section; their definitions are listed in Aggregate Design. The record() call sits in the named factory and in domain methods, never in __construct. The reason is reconstitution, the assembly of an aggregate from stored data. Doctrine bypasses the constructor when hydrating, but a hand-written Order::reconstitute() does call it – and if record() were in there, every load of an order would announce its creation again. Reconstitution as a special kind of factory is covered in Supporting Tactical Patterns.

The second half of the lifecycle is handled by the command handler. It saves the aggregate and only then collects the recorded events through releaseEvents():

php src/Ordering/Application/Handler/PlaceOrderHandler.php (excerpt)
1$order = Order::place(OrderId::generate(), $customerId);2 3$this->orders->save($order); // only persists the aggregate4$this->em->flush();          // writes the SQL; the commit is driven by the doctrine_transaction middleware5 6foreach ($order->releaseEvents() as $event) {7    $this->eventBus->dispatch($event);8}

The doctrine_transaction middleware opens a transaction before the handler and commits it only after the handler returns. So flush() by itself commits nothing, and the dispatch runs inside the open transaction. For synchronous listeners in the same process, that is fine: if the transaction fails, their writes disappear too. Anything that leaves the process (a broker, an email, an external service) goes through the Outbox.

The order “save first, then publish” is the book's choice, not the only option. Publishing before the flush would announce to recipients a change the database might have rejected. Without the middleware, when flush() itself commits, the opposite risk appears: if the process crashes between saving and publishing, the event is lost. Neither variant comes for free.

Jimmy Bogard also argues for dispatching inside the transaction. In his view, side effects belong in the same logical transaction as the change that triggered them [14]. If you want to defer delivery instead, Symfony offers the dispatch_after_current_bus middleware and the DispatchAfterCurrentBusStamp stamp, which releases the message only after the current handler finishes successfully [15]. Only a transactional outbox removes the risk of a lost event: the event and the aggregate change are written in one transaction. Full wiring into Symfony (the repository, the event bus over Messenger) is described in Implementation in Symfony 8, and the outbox in Outbox Pattern.

Frequently asked questions

What is the difference between an Entity and a Value Object?

An Entity has a unique identity (ID) that distinguishes it from other instances even when they share the same attributes. Two users with the same name and email are still two different entities. A Value Object has no identity and is compared by the values of all its attributes – typical examples are Money, Address, and Email. An Entity can change over time, while a Value Object is usually immutable. Both concepts are compared in the Entities section and the Value Objects section.

What is a Value Object for?

A Value Object encapsulates a domain concept defined only by its values, not by identity – for example, an amount of money with a currency, a range of calendar days, or an email address. It moves validity rules and domain behavior close to the data they describe, and it eliminates so-called Primitive Obsession (using primitive types where a domain concept belongs). The immutability of a Value Object makes it easier to reason about the code and about concurrent access. More in the Value Objects section.

What is an Aggregate, and why does its boundary matter?

An Aggregate is a group of domain objects that change as one unit. Access to its internal parts goes exclusively through the root entity (Aggregate Root). The aggregate boundary is usually also the boundary of transactional consistency: whatever is inside must be in a valid state after every operation. A well-defined aggregate prevents violations of domain invariants and makes it easier to decide what can change concurrently. A detailed analysis is in the Aggregates section.

What is a Repository for in DDD?

A Repository gives the domain layer a collection-like interface for saving and loading aggregates, without the domain having to know the specific persistence technology. The actual storage in the database is handled by the infrastructure layer, which implements the interface. This lets you test the domain against an in-memory repository and replace the storage without touching domain rules. More in the Repositories section.

When should you use a Domain Service instead of a method on an Entity?

A Domain Service fits where an operation naturally belongs to no Entity or Value Object. It coordinates several aggregates or calculates over the data it receives. Input from an external system is supplied by the caller, or by a domain interface implemented in the infrastructure. When the behavior naturally belongs in an entity method, the method takes precedence. A Domain Service is not an application coordinator; it holds stateless domain logic. An analysis and typical use cases are in the Domain Services section.

What is a Domain Event, and what is it for?

A Domain Event is an immutable record that something significant happened in the domain – for example, “the order was confirmed” or “the payment was received.” Events let you decouple the parts of the system that react to changes from the parts that cause them: instead of a direct call, an event is published and interested parties process it. In DDD, events are also the basis of Event Sourcing. Between Bounded Contexts, they travel only after translation into integration events. A detailed analysis is in the Domain Events section.