Chapter 10·Architecture·Implementation in Symfony 8
Implementation in Symfony 8
DDD concepts translated into Symfony 8: project structure by Bounded Context, aggregate persistence through Doctrine, Messenger configuration, and Doctrine custom types for value objects.
The diagram shows the boundary between pure DDD code (green area) and Symfony infrastructure
(orange area). Everything in the green area is plain PHP with no framework dependency, testable
in isolation, and portable between projects. The book deliberately allows the domain only symfony/uid for generating
identities and, from Doctrine, the mapping attributes and collections (Doctrine\ORM\Mapping, Doctrine\Common\Collections). The Symfony layer implements contracts
defined by the domain (repository interface, event dispatch) and provides HTTP, persistence, and messaging.
FIG. 10.1-AThe boundary between DDD and Symfony
The direction of dependencies is unambiguous: Symfony depends on the domain (it implements its interfaces), never the other way around.
From Symfony, the domain layer imports only Symfony\Component\Uid. The only traces of infrastructure in it
are the Doctrine mapping attributes (see the mapping choice). That is why
Doctrine can be replaced with another ORM, and Messenger with another bus system, without touching domain
logic; only the metadata gets rewritten. Hexagonal, onion, and clean architecture
all formalize this direction of dependencies. The chapter on architectural styles compares them.
The default Symfony structure (src/Controller, src/Entity, src/Repository) sorts files by technical role. A vertical slice sorts them by Bounded Context: each context keeps its domain, infrastructure, and feature folders together. Even the Symfony Best Practices allow the deviation: the recommendation of the default structure comes with the caveat “Unless your project follows a development practice that imposes a certain directory structure” [1]. An example:
The tree shows both ways of organizing code that the book uses. UserManagement sorts application code into feature folders, while Ordering keeps the classic Domain/Application/Infrastructure layers. When each one pays off is covered in Vertical Slice Architecture. Identifiers have no shared ancestor: each context has its own UserId or OrderId (the reason is in DDD Building Blocks).
Dependencies between contexts go through the Application layer or through events, never through a direct import of another context's domain classes. The only exception is identifiers such as ShipmentId, which carry no behavior of the foreign model.
FIG. 10.2-AProject structure with Bounded Contexts
You enter an aggregate through the aggregate root. The class extends the base AggregateRoot,
the constructor is private, and creation goes through a named factory method
(User::register(), Order::place()). That way the aggregate cannot be created
in an inconsistent state. The definition of an entity is in the chapter
DDD Building Blocks; here the topic is what it looks like in Symfony.
Implementation details:
final class User extends AggregateRoot. The base class provides record()
and releaseEvents(), behavior shared by all aggregates instead of
a copy in every entity. final does not get in the way of a mapped entity: native lazy objects in PHP 8.4
work on the original class and create no subclass
[2], and DoctrineBundle 3
no longer lets you turn them off (analysis in the chapter Aggregate Design).
Private constructor + register() factory. The only permitted way to create the aggregate.
If another category appeared (a user imported from LDAP), another
factory would be added, not a switch inside the constructor. The UserRegistered event is recorded
in the factory, not in the constructor. Reconstituting a stored aggregate must not raise
any event. Doctrine bypasses the constructor during hydration, but a custom mapper
(Persisted Object Pattern) does call it, through reconstitute().
VOs stored directly, not as primitives.UserId, Email, UserName,
and HashedPassword are property types. Doctrine hydrates them through custom types
(user_id, email_vo) or #[ORM\Embedded]. No re-validation in getters.
#[ORM\Version] for optimistic locking. A concurrent modification of the aggregate
ends with an OptimisticLockException, which the application layer translates into a retry.
Method names from the Ubiquitous Language.rename() instead of setName(),
changeEmail() instead of updateEmail(). Domain language, not a CRUD vocabulary.
In Symfony 8, a value object is written as a final readonly PHP class.
Validation belongs in the constructor, and equality is computed from values, not from identity.
A detailed analysis of VO semantics is in the chapter DDD Building Blocks:
UserName shows what a value object brings: the type enforces the invariant “a name is not empty
and has a reasonable length.” Calling code has no way to pass in an empty
string. If it tried, it would get an exception in the constructor, not later in the repository.
#[ORM\Embeddable] tells Doctrine that the VO is stored in the columns of the owner's table
(no separate table for the VO).
The third kind of value object is the aggregate's identity. It is generated in the application,
not in the database, so the handler knows the ID before the aggregate is saved:
Uuid::v7() from the symfony/uid package returns a time-ordered UUID, suitable
as a primary key (sequential writes do not fragment the B-tree index). The same pattern applies
to OrderId or PaymentId; the value is always exposed by the public readonly
property $value, never by a value() method.
Property hooks and asymmetric visibility
Symfony 8 requires PHP 8.4, so a value object can also be written without
readonly. The book still sticks with it, for two reasons.
Asymmetric visibility (public private(set) string $value) replaces the pair of
a private property plus a getter. It suits objects with wither methods that need to
overwrite a value inside the class after clone. For a value object,
readonly is stricter: after initialization it forbids any write, even from inside the class,
so immutability does not depend on the author's discipline. That is why VOs stay final readonly throughout the book.
Property hooks tempt you to move validation from the constructor into a set hook.
For a value object, that does not pay off. A hook cannot be combined with readonly (PHP
reports “Hooked properties cannot be readonly”), so the VO would lose its immutability.
During hydration, Doctrine writes the raw value through ReflectionProperty::setRawValue()
and bypasses the hook just as it bypasses the constructor. Validation in a hook therefore protects nothing that
the constructor would not.
In Symfony 8, a repository is split into a pair: an interface in the domain + a Doctrine implementation in the infrastructure. Domain code relies only on the interface, so swapping persistence happens in a single file:
DoctrineUserRepository implements the domain interface UserRepository through Doctrine ORM.
save() only queues the aggregate for storage through persist(); flush and commit are done by
the transaction middleware on the command bus, so one use case corresponds to one transaction.
The application layer publishes domain events as a separate step, only after flush(),
so that listeners see the written state.
10.06 Persisted Object Pattern – a separate persistence model#
A domain layer without a single piece of persistence metadata requires a second object
model. The domain class stays a POPO without attributes; next to it, in the infrastructure layer, lives
a separate persistence class with all the Doctrine attributes, and a mapper between them
translates in both directions. The book calls this construction the Persisted
Object Pattern; in the literature the name persistence model has taken hold,
and its general parent pattern is Fowler's Data Mapper (PoEAA, 2002)
[4].
Yet the two most frequently cited advocates of a pure domain are against it. Vladimir Khorikov
calls a full-fledged persistence model too expensive. The complexity grows with every
one-to-many and many-to-many association. On top of that, you lose the ORM change tracking that
reliable domain events depend on
[5].
Matthias Noback calls separate entities an “expensive and unnecessary form of
decoupling” and recommends instead an ORM entity enriched with domain methods,
invariants, and custom exceptions
[6]. The only
scenario he accepts is evolving the aggregate design independently of the database schema.
By his own account, he has no experience with it himself, and the projects with separate entities he
had heard of had no such need.
The section stays in the book because it shows what such a separation costs. The example is
complete, so you can calculate that cost yourself.
The hand-written mapper is the biggest cost item of the pattern, and since Symfony 7.4 there has been
a stable symfony/object-mapper component for it
[7]. The attribute
#[Map(target: UserPersistenceModel::class)] describes the conversion declaratively, and
ObjectMapperInterface::map() performs it. Hand-written code then remains only where the
shapes of the two models diverge, typically with value objects composed of several
columns. The risk of drift does not go away, though: the component maps what you describe to it
and does not report a missing field.
The remaining examples in the book stay with attributes directly on aggregates and do not develop the Persisted Object
Pattern further. The principles are the same; the only difference is that each aggregate needs its own mapper.
The Implementing entities section declares properties directly of type Email
or UserId. Their hydration is handled by a Doctrine custom type, a converter
between a database primitive and a value object.
Why neither type has a getName() method is explained in Aggregate Design.
The NAME constant is only a named reference that can be used in the #[ORM\Column] attribute
instead of a string. Without getSQLDeclaration(), the column length
would be dictated by the parent StringType.
XML mapping (User.orm.xml) can do the same without attributes in the class, but it does not
separate the domain from the ORM; it only moves the metadata into another format. With the annotation
and YAML drivers removed in ORM 3, the only options left besides attributes are XML and the rarely used PHP mapping
[8]. Tooling around
Doctrine supports both variants worse than attributes. If you want strict separation, the solution is
in the Persisted Object Pattern – a separate persistence model section.
Order status, user role, task priority. Finite sets of values that used to be modeled with class constants
have a native type: the enum. Static analysis catches a typo in a case name, and the runtime type check rejects an unknown value.
transitionTo() is an alternative to named transitions, not an addition to them. The canonical aggregate
from Aggregate Design uses markPaid(), ship(),
and cancel(), because each operation carries its own invariant and its own event.
OrderPaid says more than OrderStatusChanged(Confirmed, Paid). If you keep both,
you get two paths into the same state that record different events: markPaid()
emits OrderPaid, transitionTo() emits OrderStatusChanged. A projection that
listens to only one of them then sees the change on one path and misses it on the other.
A generic transition pays off where there are many states, the transitions are uniform,
and distinct events would bring nothing: a ticket workflow, document states in an approval process.
An order is not one of those cases.
A domain service encapsulates a rule that naturally belongs to no aggregate
or value object. Typically it is an operation over two or more aggregates
(MoneyTransferService between two accounts) or a stateless calculation with external
input: a currency conversion, a tax calculation by jurisdiction.
Before reaching for a domain service, one question always comes first: doesn't this belong in the aggregate?
The rule “only a confirmed order can be paid” is a pure invariant of the Order aggregate.
Only Order knows its status, and only it may change it. A domain service in the same place
is an anti-pattern: it weakens the aggregate and leads to an anemic model.
Order::recordPayment() encapsulates both the rule and the state transition inside the aggregate.
The only way to create a Payment for an order goes through this method.
The example is an illustrative variant of markPaid() from Aggregate Design,
and it rests on four classes that the book does not develop further: Payment, PaymentId,
PaymentMethod, and PaymentRecorded. The canonical model does not model payment as a separate aggregate;
it keeps it in the Payment context across the boundary, where a command is sent. A project
following the book should therefore use markPaid(); this listing only shows an alternative in which the payment
is created inside the order. The invariant “only a confirmed order can be paid” is then enforced by
the aggregate itself, not by the hope that someone calls the right service. The application handler then has only
a coordinating role. The terms command and handler are explained in the
section on application services, and in detail in the chapter CQRS:
The handler writes two aggregates in one transaction. That is a deviation from the rule of thumb
one aggregate per transaction, and none
of Vernon's exceptions covers it. Splitting it into two
transactions would allow a paid order without a payment. But according to Khononov, an invariant shared
by two aggregates is a signal that the boundary between Order and Payment lies
somewhere else. The example keeps the deviation for simplicity. The canonical model heeds that signal: it leaves payment
in the Payment context and sends the order only markPaid(). An alternative within
a single context is eventual consistency: Order records
PaymentRecorded, and Payment is created only in reaction to the event. The cost is a window during which the
payment does not exist yet, plus the need for compensation on failure.
The Specification Pattern (Eric Evans, DDD, ch. 9) encapsulates a domain rule
in a separate object with an isSatisfiedBy() method. The rule “an order
is eligible for shipping” then exists in one place. The same specification serves
validation in the aggregate, filtering of collections, and selection in the repository. Small rules
are composed with the and(), or(), and not() combinators into more complex ones, without copying
conditions around the code.
The full treatment, including the PHP implementation, the combinators, and the integration with Doctrine,
is in the Specification Pattern section
of the Supporting Tactical Patterns chapter.
A domain event is a fact in the past tense: the registration took place, the payment was recorded. In Symfony 8, code models it as an immutable PHP class that the aggregate records when its state changes:
UserRegistered carries the minimum needed to restore context: the user ID, the email, and the time of registration.
Unlike the order events, which carry value objects (see
Aggregate Design), these are primitives. The Identity context
(Authorization in DDD) also subscribes to the event, which is why it has the shape
of an integration event.
Listeners and external consumers assemble their reaction from these three values without reaching back into UserRepository.
The constructor matches the call record(new UserRegistered(...)) in the
User::register() factory in the Implementing entities section.
The trio of command, handler, and bus appears here for the first time, so a brief word on the terms.
A command is an immutable object describing an intent:
“register a user with this name and email.” It has no behavior and carries only the use case
data. A handler is the class that carries out the command: it loads the aggregates, calls
the domain method, and saves the result.
The command bus connects the two. The caller hands the command to the bus (MessageBusInterface
from Symfony Messenger), and the bus finds the matching handler by message type. Between
the dispatch and the handler, middleware is inserted as well: validation runs the Symfony
Validator over the command, and doctrine_transaction wraps the handler in a database
transaction.
The book uses the bus this early because it is the idiomatic Symfony path: the controller
does not know the handler, only a description of the intent. The same command can later be processed asynchronously
without touching the calling code. The full treatment, including separate buses for commands
and queries, is in the chapter CQRS.
In Symfony 8, then, an application service takes the form of a command or query handler. It loads aggregates through the repository,
calls a domain method, and writes the result; no domain rules live in it:
RegisterUserHandler and GetUserProfileHandler are application services (command and query handlers).
They coordinate the use case and delegate domain logic to the entity or a domain service.
Reading here goes through the aggregate's repository, that is, through the write model. For four fields that is enough,
and it adds no unnecessary layer. As soon as the profile starts showing the number of orders or
the membership level, it stops working out: the data lives in other contexts, and the aggregate has nowhere
to get it from. That boundary is the subject of the chapter on CQRS,
where GetUserProfileHandler reads from its own read repository and returns a richer
UserProfileViewModel.
A controller is an adapter between HTTP and the application layer. It may validate the input format,
transform it into a command/query, dispatch it, and translate a domain exception
into an HTTP response. It may not carry domain rules, call repositories directly,
or manipulate aggregates.
For this, Symfony offers #[MapRequestPayload]: it deserializes and validates a JSON
request directly into a typed command. For classic HTML forms there is the
#[MapRequestPayload(acceptFormat: 'form')] variant, or Symfony Form.
MapRequestPayload takes over deserialization, validation through the Symfony Validator
(the #[Assert\…] attributes on the command), and the translation of a validation error into HTTP 422.
The controller thus has only three responsibilities: the dispatch, mapping domain exceptions
to HTTP, and returning the response.
The controller is thin, so the weight of testing sits below it. Aggregates are tested as
plain PHP without a kernel. Application handlers are covered by a unit test with an in-memory fake
repository. The fake does not verify the unique constraint, its translation into a domain exception, or the transactional
behavior; those belong in an integration test against a test database.
The chapter Testing DDD goes through concrete tests layer by layer.
Authorization stays outside the controller as well; it has its own chapter,
Authorization in DDD. In brief:
the question “may this user perform this use case on this object” is answered by
the use case layer through a Symfony Voter, while domain invariants stay
in the aggregate. The chapter introduces a four-layer framework, from the HTTP firewall to rules
at the field level, and shows why domain rules do not belong in a Voter.
In Symfony 8, the DI Container binds interfaces from the domain layer to concrete implementations in the infrastructure.
The configuration determines which class autowiring injects when a handler type-hints UserRepository:
The alias ensures that the Symfony DI Container injects the same instance of DoctrineUserRepository
everywhere a dependency type-hints UserRepository. Domain models, value objects,
and events are excluded from auto-registration; they are not services but data. If you do not want
to maintain glob patterns in services.yaml, mark such a class with the
#[Exclude] attribute from Symfony\Component\DependencyInjection\Attribute; the container
then skips it regardless of resource:.
Autowiring with separate Bounded Contexts
In larger projects with several Bounded Contexts, autowiring is configured for each context separately.
Each context gets its own block in services.yaml, so the boundary shows up in the service container too.
The following configuration replaces the App\: block from the previous example; it does not add to it. The difference
is noticeable: the catch-all App\: also registers whatever was forgotten, while a per-context list has nothing
of the kind. A class in a directory missing from the list is not a service at all. If nothing depends on it
(a handler, a controller), the error is reported not by lint:container but only at runtime.
The last eight lines are aliases from interfaces to implementations. Autowiring would create most of them
on its own, because the interface and its only implementation sit in the same resource block
(see the chapter on architectural styles).
An explicit line, however, documents the choice of the default adapter, and it survives even when a real payment gateway
appears next to InMemoryPaymentGateway and the automatic alias disappears.
Symfony – The Symfony Framework Best Practices. The recommendation of attribute-based Doctrine mapping, and the caveat that allows a deviation from the default directory structure.
PHP Manual – Lazy Objects (PHP 8.4). Native lazy ghosts and lazy proxies without a generated subclass.
Doctrine ORM – Basic Mapping. Support for property hooks since ORM 3.4, and the behavior of DQL over the value stored in the column.
Martin Fowler – Data Mapper, Patterns of Enterprise Application Architecture (2002). The parent pattern of a separate persistence model.
Where does the domain layer belong in a Symfony project, and why keep it separate?
The domain layer belongs in its own directory, separate from controllers, Doctrine mapping, and infrastructure. In this book, that is src/<BoundedContext>/Domain/, for example src/UserManagement/Domain/. The isolation lets you test and refactor the model without depending on the Symfony lifecycle, and it allows you to move the domain to another technology stack. See the Project structure section.
How do you map an aggregate in Doctrine without the domain depending on the ORM?
This book uses Doctrine attributes directly on the aggregate as the pragmatic default choice: they are metadata, not behavior. A domain without a single trace of the ORM requires a separate persistence model, which this book calls the Persisted Object Pattern. The domain class stays a POPO; next to it, in the infrastructure, sits a separate persistence class with attributes and a mapper between the two. The parent pattern is Fowler's Data Mapper. Both Khorikov and Noback call this separation expensive and, in most projects, unnecessary, so it is a minority choice, not the default recommendation. Details in the Persisted Object Pattern – a separate persistence model section.
How do you tell an Application Service from a Domain Service?
A Domain Service holds pure domain logic that naturally belongs to no aggregate or value object; it is stateless and does not talk to the infrastructure. An Application Service, by contrast, orchestrates a use case: it takes input from the controller, loads aggregates through the repository, calls the domain logic, and hands the result over for persistence. An Application Service never contains domain rules, only a sequence of steps. A detailed analysis is in the Implementing application services section and the Domain services (and when not to use them) section.
Should domain operations throw exceptions or return a Result type?
In the PHP and Symfony ecosystem, exceptions are the dominant approach. When an invariant is violated, the aggregate throws a specific domain exception (for example, InsufficientFundsException). The application layer translates it into an HTTP response or a message for the user. A Result/Either type is possible in PHP, but it adds complexity without a matching benefit. Controllers react only to domain subtypes (with Messenger, unwrapped from HandlerFailedException) and never catch a generic Exception. The variants are analyzed in the Error handling strategy in DDD section.
When should you use a Doctrine Custom Type for a Value Object?
A Doctrine Custom Type fits where a value object is stored as a simple value in a single column: an email, a URL, a custom identifier. The Custom Type translates the value object into a primitive on write and reconstructs it on read. Domain code then always works with a typed object. For value objects composed of several columns, such as Money with an amount and a currency, embeddable mapping is a better fit (see Mapping in Doctrine). A detailed analysis is in the Doctrine custom types for Value Objects section.