Supporting Tactical Patterns: Specifications, Domain Services, Factories, and Modules
Alongside entities, value objects, and aggregates, Evans's book contains four more tactical patterns that practice often skips: Specification for rules expressed as standalone predicates, Domain Service for behavior that belongs to no entity, Factory for complex aggregate creation, and Module for organizing code. Each comes with PHP 8.4 examples, anti-patterns, and comparisons.
In this chapter
The chapter DDD Building Blocks covered entities, value objects, aggregates, and, only briefly, domain services and factories. Evans, however, devotes dozens of pages in Parts II and III to services, factories, specifications, and modules. Guides tend to skip them or confuse them with other patterns. This chapter shows when they are useful, how to write them in PHP 8.4, and what misusing them costs.
All four patterns come straight from Evans's book. Specification (ch. 9) turns domain predicates into composable objects. Domain Service (ch. 5) captures logic that has no natural owner among entities and value objects. Factory encapsulates the creation of aggregates with complex invariants (ch. 6; in Vernon, ch. 11). Module (also ch. 5) organizes code according to the Ubiquitous Language.
08.01 Why these patterns get overlooked#
Most online DDD guides stop at the aggregate. A developer who can tell an entity from a value object and understands invariants feels in command of tactical design. Specification, Domain Service, Factory, and Module then look like needless abstraction, because the same thing can be written with an if, a static method, or a plain package in src/. That intuition is misleading.
A small project can do without these patterns. In a non-trivial domain, which is where DDD pays off, their absence leads to bloated aggregates, an anemic model, and duplicated rules. The code then stops reflecting the structure of the domain. The patterns also build on one another, as section 08.06 shows.
08.02 Specification Pattern#
What it is
A Specification is a standalone object that encapsulates a single boolean predicate over a domain object – typically the answer to the question “does this aggregate satisfy a particular rule?” The minimal interface:
1interface Specification2{3 public function isSatisfiedBy(mixed $candidate): bool;4}
The interface is trivial; the decision behind it is not. Every rule of the domain language gets its own class with a descriptive name: “the customer is premium,” “the order qualifies for free shipping,” “the invoice is overdue.” The rule stops being a combination of ifs in the service layer and becomes a named element of the Ubiquitous Language.
Evans and Fowler formally described the pattern in their joint 1997 paper Specifications [martinfowler.com]; Evans later included it in Domain-Driven Design (2003), chapter 9, Making Implicit Concepts Explicit. Both texts start from the same premise: a rule that recurs in the domain deserves its own name and its own type.
One note on sources. The distilled DDD Reference (2015) no longer contains Specification. Under Building Blocks of a Model-Driven Design, Evans lists Layered Architecture, Entities, Value Objects, Domain Events, Services, Modules, Aggregates, Repositories, and Factories. So it is not only practice that skips the pattern; it also dropped out of the author's own summary.
When to use it
The original paper names three uses of the pattern. Selection picks a subset of objects by a criterion and can refresh the selection at any time. Validation checks that an object is fit for a given purpose. Construction-to-order describes what an object should look like without dealing with how to produce it; a candidate can then be built to order from the description. In a Symfony project, these uses show up in four typical situations:
- Complex domain rules that need to be composed. If the same motif keeps returning in different parts of the application in different combinations – “premium AND in the EU” here, “premium OR has a discount code” there – composition through Specification saves duplication and keeps the rules consistent.
- Rules usable both in the domain and in the repository. The same specification answers “does this particular object satisfy the rule?” (an in-memory predicate) and also returns every object in the database that satisfies it (a query). Both forms of the rule (PHP and a Doctrine query) live together in one class; the repository receives the specification as a query parameter (see Specification as a Doctrine query).
- Rules composed at runtime. A promo code in the admin UI has the conditions “valid for purchases over CZK 1,000 in the Czech Republic and Slovakia, except clearance items.” The domain represents it as an instance of
AndSpecificationcomposed of N sub-rules read from the database. - An aggregate validation rule. The aggregate does not check everything itself in setters; it delegates to a specification that can be read and tested on its own.
The paper adds three implementation strategies that differ in cost. A Hard Coded Specification is one class per rule, with no parameters – cheap, but it grows with the number of rules. A Parameterized Specification builds the rule at runtime from values; that is exactly what item 3 does with the promo code read from the database. A Composite Specification adds and, or, and not nodes and reads the rule as an expression. Evans and Fowler state its cost too: the composite is flexible without a pile of specialized classes, but it requires an investment in a framework. The rest of this section shows that framework so you can see what the investment involves.
When not to use it
Specification has a non-trivial cost: every rule means a new class, a new file, and a new test. It does not fit:
- Trivial conditions that occur once and contain a single if:
if ($order->totalAmount()->amountInCents > 100_000)does not need its own class. - Rules that are actually part of an aggregate invariant (and therefore belong directly in it as a private method).
- Configuration and technical flags – a Specification should represent a domain rule, not the condition “has the feature flag enabled.”
The Evans and Fowler paper has its own section, When Not to Use Specification, and its criterion is sharper than the list above. If an object represents an actual domain entity rather than placing conditions on another, possibly hypothetical, entity, the pattern does not belong there. The authors illustrate this with the pair Route and Route Specification: a route is something the domain knows and that has identity. A route specification only describes what kind of route would qualify – no such route needs to exist yet.
Composition through combinators
The value of the pattern comes from composition through the boolean combinators and, or, and not. Instead of a tangle of ifs and elses, you get an algebraic expression over named atoms. The class hierarchy:
Interface and abstract composite
The full interface exposes all three combinators. It extends the single-method version from the start of the section and replaces it for the rest of the chapter. An abstract class then implements the combinators through AndSpecification, OrSpecification, and NotSpecification:
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7/**8 * Domain specification – a first-class object encapsulating a boolean predicate.9 *10 * @template T11 */12interface Specification13{14 /** @param T $candidate */15 public function isSatisfiedBy(mixed $candidate): bool;16 17 /**18 * @param Specification<T> $other19 * @return Specification<T>20 */21 public function and(self $other): self;22 23 /**24 * @param Specification<T> $other25 * @return Specification<T>26 */27 public function or(self $other): self;28 29 /** @return Specification<T> */30 public function not(): self;31}
Concrete specifications do not implement the combinators; the abstract class supplies them:
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7/**8 * @template T9 * @implements Specification<T>10 */11abstract class CompositeSpecification implements Specification12{13 /** @param T $candidate */14 abstract public function isSatisfiedBy(mixed $candidate): bool;15 16 public function and(Specification $other): Specification17 {18 return new AndSpecification($this, $other);19 }20 21 public function or(Specification $other): Specification22 {23 return new OrSpecification($this, $other);24 }25 26 public function not(): Specification27 {28 return new NotSpecification($this);29 }30}
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7/**8 * @template T9 * @extends CompositeSpecification<T>10 */11final class AndSpecification extends CompositeSpecification12{13 /**14 * @param Specification<T> $left15 * @param Specification<T> $right16 */17 public function __construct(18 private readonly Specification $left,19 private readonly Specification $right,20 ) {}21 22 public function isSatisfiedBy(mixed $candidate): bool23 {24 return $this->left->isSatisfiedBy($candidate)25 && $this->right->isSatisfiedBy($candidate);26 }27}
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7/**8 * @template T9 * @extends CompositeSpecification<T>10 */11final class OrSpecification extends CompositeSpecification12{13 /**14 * @param Specification<T> $left15 * @param Specification<T> $right16 */17 public function __construct(18 private readonly Specification $left,19 private readonly Specification $right,20 ) {}21 22 public function isSatisfiedBy(mixed $candidate): bool23 {24 return $this->left->isSatisfiedBy($candidate)25 || $this->right->isSatisfiedBy($candidate);26 }27}
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7/**8 * @template T9 * @extends CompositeSpecification<T>10 */11final class NotSpecification extends CompositeSpecification12{13 /** @param Specification<T> $inner */14 public function __construct(private readonly Specification $inner) {}15 16 public function isSatisfiedBy(mixed $candidate): bool17 {18 return !$this->inner->isSatisfiedBy($candidate);19 }20}
Domain specification
Three concrete rules from the Ordering context stand on this skeleton. Each carries a descriptive domain name and inherits the and/or/not combinators.
The specifications read totalAmount(), customerId, and shippingAddress from the aggregate. The canonical Order from Aggregate Design has the first two, but not the third. That chapter shows ShippingAddress only as an embeddable value object, and the aggregate does not carry it. The examples here assume an order extended with the property public readonly ShippingAddress $shippingAddress. The factory variant in section 08.04 has no address – each example extends the canonical Order only with what its pattern needs.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Specification;6 7use App\Ordering\Domain\Model\Order;8use App\SharedKernel\Domain\Money;9use App\SharedKernel\Domain\Specification\CompositeSpecification;10 11/**12 * The order qualifies for free shipping if its total value13 * reaches or exceeds the set threshold.14 *15 * @extends CompositeSpecification<Order>16 */17final class EligibleForFreeShipping extends CompositeSpecification18{19 public function __construct(private readonly Money $threshold) {}20 21 public function isSatisfiedBy(mixed $candidate): bool22 {23 assert($candidate instanceof Order);24 25 $total = $candidate->totalAmount();26 27 return $total->currency === $this->threshold->currency28 && $total->amountInCents >= $this->threshold->amountInCents;29 }30}
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Specification;6 7use App\Ordering\Domain\Model\Order;8use App\SharedKernel\Domain\Specification\CompositeSpecification;9 10/**11 * The order's shipping address is in an EU member state.12 * The list of countries is part of the rule – the specification13 * needs no input from outside.14 *15 * @extends CompositeSpecification<Order>16 */17final class InEUCountry extends CompositeSpecification18{19 private const array EU_COUNTRIES = [20 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR',21 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL',22 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE',23 ];24 25 public function isSatisfiedBy(mixed $candidate): bool26 {27 assert($candidate instanceof Order);28 29 return in_array(30 $candidate->shippingAddress->countryCode,31 self::EU_COUNTRIES,32 true,33 );34 }35}
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Specification;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\ValueObject\CustomerId;9use App\SharedKernel\Domain\Specification\CompositeSpecification;10 11/**12 * The customer is not on the domain blacklist (e.g., fraud detection).13 *14 * @extends CompositeSpecification<Order>15 */16final class NotInBlacklist extends CompositeSpecification17{18 /** @param list<CustomerId> $blacklist */19 public function __construct(private readonly array $blacklist) {}20 21 public function isSatisfiedBy(mixed $candidate): bool22 {23 assert($candidate instanceof Order);24 25 foreach ($this->blacklist as $blocked) {26 if ($blocked->equals($candidate->customerId)) {27 return false;28 }29 }30 31 return true;32 }33}
The assert($candidate instanceof Order) call in the examples narrows the type for static analysis, not for runtime. With zend.assertions=-1, it is not even compiled in production, so it is no runtime safeguard. The real check comes from the @template T type parameter together with PHPStan or Psalm, which verify the composition statically.
Composition in the application layer
The marketing campaign “free shipping for purchases from CZK 1,000 in the EU, except for blacklisted customers” is a trio of atomic specifications joined by the and combinator. Instead of a triple-nested if, you get one readable expression:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Service;6 7use App\Ordering\Application\BlacklistRegistry;8use App\Ordering\Domain\Model\Order;9use App\Ordering\Domain\Specification\EligibleForFreeShipping;10use App\Ordering\Domain\Specification\InEUCountry;11use App\Ordering\Domain\Specification\NotInBlacklist;12use App\SharedKernel\Domain\Currency;13use App\SharedKernel\Domain\Money;14 15final class FreeShippingPolicy16{17 public function __construct(private readonly BlacklistRegistry $blacklist) {}18 19 // The policy answers; it does not change state. What to do with the entitlement20 // (zero shipping cost, a discount line) is decided by the checkout handler that calls it.21 public function isEligible(Order $order): bool22 {23 // CZK 1,000 in hellers – Money holds the amount as an integer.24 $promo = (new EligibleForFreeShipping(new Money(100_000, Currency::CZK)))25 ->and(new InEUCountry())26 ->and(new NotInBlacklist($this->blacklist->all()));27 28 return $promo->isSatisfiedBy($order);29 }30}31 32// --- src/Ordering/Application/BlacklistRegistry.php ---33namespace App\Ordering\Application;34 35use App\Ordering\Domain\ValueObject\CustomerId;36 37// Port: the Infrastructure layer supplies the list of blacklisted customers38// (fraud detection, a manually maintained list). The specification receives a ready list.39interface BlacklistRegistry40{41 /** @return list<CustomerId> */42 public function all(): array;43}
In a test, the rule can be broken down into atoms and each one verified separately. When the product team decides the blacklist should no longer be checked, one line disappears from the composition, and nobody has to read through a tight if deep in the service layer.
The policy returns a bool and leaves the aggregate alone. The checkout handler consumes the result: it puts zero shipping cost into the price calculation or records it as a discount line. The canonical Order therefore needs no extra method, and the specification stays a pure query over state.
Two patterns from the paper that never caught on
The Specifications paper contains two follow-up patterns that made it into neither the books nor PHP practice. Both address a question that isSatisfiedBy() cannot answer.
Subsumption compares specifications with each other instead of a specification with a candidate. The isGeneralizationOf() method answers whether one rule is more general than another. It is used for matching supply with demand, where you describe both sides with a specification and no concrete object exists yet.
Partially Satisfied Specification adds remainderUnsatisfiedBy(), which returns the remaining specification – that is, what is still left to satisfy. Instead of false, the user gets the answer “missing a shipping address in the EU.”
The method belongs in the Specification interface, not only in the composite: AndSpecification calls it on its children, which it knows only as Specification. CompositeSpecification supplies a default body, so leaf specifications do not have to add anything:
1// The interface keeps and/or/not from the full interface above; only a fifth method is added.2interface Specification3{4 /** @param T $candidate */5 public function isSatisfiedBy(mixed $candidate): bool;6 7 /**8 * @param Specification<T> $other9 * @return Specification<T>10 */11 public function and(self $other): self;12 13 /**14 * @param Specification<T> $other15 * @return Specification<T>16 */17 public function or(self $other): self;18 19 /** @return Specification<T> */20 public function not(): self;21 22 /**23 * Returns a specification describing what the candidate has not yet satisfied,24 * or null if it has satisfied everything.25 *26 * @param T $candidate27 * @return Specification<T>|null28 */29 public function remainderUnsatisfiedBy(mixed $candidate): ?Specification;30}31 32 33abstract class CompositeSpecification implements Specification34{35 // Default implementation for leaves and composites36 public function remainderUnsatisfiedBy(mixed $candidate): ?Specification37 {38 return $this->isSatisfiedBy($candidate) ? null : $this;39 }40}
1public function remainderUnsatisfiedBy(mixed $candidate): ?Specification2{3 $left = $this->left->remainderUnsatisfiedBy($candidate);4 $right = $this->right->remainderUnsatisfiedBy($candidate);5 6 if ($left !== null && $right !== null) {7 return new self($left, $right);8 }9 10 return $left ?? $right;11}
Every combinator has to implement the method, and for or and not the answer is no longer unambiguous. The benefit is just as clear: a form or an API returns a rejection reason derived from the rule that decided, instead of a hand-written message that drifts away from the logic over time.
Specification as a Doctrine query
A specification also serves in a second role – as a query parameter for the repository. Instead of a method like findEligibleForFreeShippingInEU(): array, which would multiply with every new combination of rules, the repository receives any specification, turns it into a query, and returns the result. The specification carries the rule; the repository knows how to translate it into persistence.
This collaboration is often called double dispatch, but in the strict sense the term fits only Evans's variant from chapter 9. There, the repository passes itself to the specification (satisfyingElementsFrom($this)), and the specification calls back the repository's specialized query method. The variant in this section has no callback: the repository asks the specification for an expression and runs it itself.
One thing decides the design: what the specification returns. Mutating a passed-in QueryBuilder is tempting, but it leads to a dead end: a method with a void return type cannot be composed, so or and not cannot be translated. Doctrine has its own intermediate representation for this. Doctrine\Common\Collections\Criteria builds expressions through Criteria::expr() and offers eq, neq, gt, gte, lt, lte, in, notIn, contains, startsWith, endsWith, isNull, memberOf, and the combinators andX, orX, and not. The specification therefore returns an expression, not a side effect:
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain\Specification;6 7use Doctrine\Common\Collections\Expr\Expression;8 9/**10 * A specification that can express its rule as a Doctrine expression.11 * The specification knows the rule; the repository knows how to run12 * the expression against the database.13 *14 * @template T15 * @extends Specification<T>16 */17interface QuerySpecification extends Specification18{19 public function toExpression(): Expression;20}
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Specification;6 7use App\Ordering\Domain\Model\Order;8use App\SharedKernel\Domain\Money;9use App\SharedKernel\Domain\Specification\CompositeSpecification;10use App\SharedKernel\Domain\Specification\QuerySpecification;11use Doctrine\Common\Collections\Criteria;12use Doctrine\Common\Collections\Expr\Expression;13 14/**15 * @extends CompositeSpecification<Order>16 * @implements QuerySpecification<Order>17 */18final class EligibleForFreeShipping extends CompositeSpecification implements QuerySpecification19{20 public function __construct(private readonly Money $threshold) {}21 22 public function isSatisfiedBy(mixed $candidate): bool23 {24 assert($candidate instanceof Order);25 26 $total = $candidate->totalAmount();27 28 return $total->currency === $this->threshold->currency29 && $total->amountInCents >= $this->threshold->amountInCents;30 }31 32 public function toExpression(): Expression33 {34 return Criteria::expr()->andX(35 Criteria::expr()->eq('totalCurrency', $this->threshold->currency->value),36 Criteria::expr()->gte('totalAmount', $this->threshold->amountInCents),37 );38 }39}
The query form assumes that the order holds its total in the mapped properties totalAmount and totalCurrency. The canonical Order computes the sum from its items at runtime, and Criteria works only with mapped properties, so without such denormalization the query has nothing to filter on.
The repository then exposes a general match() method. Doctrine\ORM\EntityRepository implements the Selectable interface, so it can run Criteria directly:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Repository;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\Repository\OrderRepository;9use App\SharedKernel\Domain\Specification\QuerySpecification;10use Doctrine\Common\Collections\Criteria;11use Doctrine\ORM\EntityManagerInterface;12 13final class DoctrineOrderRepository implements OrderRepository14{15 public function __construct(private readonly EntityManagerInterface $em) {}16 17 /**18 * @param QuerySpecification<Order> $spec19 * @return list<Order>20 */21 public function match(QuerySpecification $spec): array22 {23 $criteria = new Criteria($spec->toExpression());24 25 return array_values(26 $this->em->getRepository(Order::class)->matching($criteria)->toArray(),27 );28 }29}
The same Criteria also works over an in-memory ArrayCollection, because the collection implements the Selectable interface just like the repository. When a query needs a join or ordering across an association, the expression goes into a QueryBuilder through addCriteria(), and the rest of the query stays hand-written. The join follows an association inside the aggregate; the order refers to the customer only through CustomerId:
1/**2 * @param QuerySpecification<Order> $spec3 * @return list<Order>4 */5public function matchWithItems(QuerySpecification $spec): array6{7 return $this->em->createQueryBuilder()8 ->select('o', 'i')9 ->from(Order::class, 'o')10 ->join('o.items', 'i')11 ->addCriteria(new Criteria($spec->toExpression()))12 ->getQuery()13 ->getResult();14}
Both roles of the specification (the in-memory predicate and the translation into a query) sit in one class. When the PHP and database forms start to diverge, code review shows it on a single screen. Nothing enforces their agreement, though – they are two independent implementations of the same rule. The safeguard is a contract test: over the same set of test data, it verifies that isSatisfiedBy() marks the same objects that match() returns from the database. When the two versions drift apart, the test fails before production does.
Benjamin Eberlei described the path from a repository with too many methods, through Doctrine Criteria, to specifications in On Taming Repository Classes in Doctrine (2013). His specifications modify a passed-in QueryBuilder, which is the variant this section abandons for the sake of composition; the happyr/doctrine-specification package also grew out of his article. Kévin Gomez followed up with On Taming Repository Classes in Doctrine… Among other things (February 7, 2015).
Limits: what Criteria can and cannot handle
Because the specification returns an expression, the combinators translate as directly as the predicate: AndSpecification to andX, OrSpecification to orX, and NotSpecification to not.
1// The class declaration gains the interface; otherwise match() rejects it as input:2// final class AndSpecification extends CompositeSpecification implements QuerySpecification3 4public function toExpression(): Expression5{6 if (!$this->left instanceof QuerySpecification7 || !$this->right instanceof QuerySpecification8 ) {9 throw new \LogicException(10 'Only a composition of QuerySpecification can be translated into a query.',11 );12 }13 14 return Criteria::expr()->andX(15 $this->left->toExpression(),16 $this->right->toExpression(),17 );18}
The combinator implements QuerySpecification, but its operands do not have to be query specifications. The type check on the input of match() therefore does not reach the leaves, and a mismatch surfaces only as a runtime exception. In exchange, or and not can be composed too, not only conjunction.
Static analysis, on the other hand, is stricter than runtime. The and() method in CompositeSpecification declares the return type Specification, so both PHPStan and Psalm reject the composed specification as input to match(), even though it passes at runtime. The caller narrows the type itself, for example with assert($promo instanceof QuerySpecification) before calling match().
There is also no risk of parameter-name collisions, which a manual setParameter() in a QueryBuilder invites: Criteria generates its own placeholders, so two sub-specifications with the same threshold value do not overwrite each other.
The real limits lie elsewhere. Criteria compares strictly in eq and neq, so comparing DateTimeImmutable instances behaves differently than in SQL. Custom DQL functions, joins, aggregations, and subqueries cannot be expressed. Fields in the expression refer to entity properties, not columns, so a rule over an association cannot get into the expression without addCriteria() and a manual join. For such a query, the right choice remains a dedicated repository method (findOrdersEligibleForPromo()) that writes the rule directly in DQL and is tied to the in-memory specification by a contract test.
The whole framework from this section also exists ready-made. happyr/doctrine-specification supports Doctrine ORM 3 and extends the repository with match(); rules are composed through Spec::andX() and Spec::orX(). It also separates filtering from result modifiers (ordering, hydration), which the hand-rolled skeleton in this chapter cannot do. The examples above explain what the package does internally. In a project where specifications are not the subject of teaching, the package is the cheaper choice.
For a deep theoretical grounding of the pattern: Evans, E., Domain-Driven Design (2003), chapter 9, Making Implicit Concepts Explicit; Evans & Fowler, the paper Specifications (1997), available at martinfowler.com. Practical application to aggregates: Vernon, V., Implementing Domain-Driven Design (2013). For the Doctrine part: Eberlei, B., On Taming Repository Classes in Doctrine (2013); Gomez, K., On Taming Repository Classes in Doctrine… Among other things (2015), and the doctrine/collections documentation on Criteria and Selectable.
08.03 Domain Services#
DDD Building Blocks introduces the domain service, and Implementation in Symfony 8 shows how to register it in the container. This section is about the decision criteria: when a service should exist, when it is only logic torn out of an entity, and where the boundary with the Application layer runs.
What it is
A Domain Service is a stateless object with domain logic that has no natural owner among the model's entities and value objects. In chapter 5 of Domain-Driven Design (2003), Eric Evans sums up the criterion in three points: the operation relates to a domain concept, but (1) it does not belong to any entity or value object as their natural method, (2) its interface is made up of other elements of the domain model, and (3) it has no state of its own.
The signal is an operation that no entity could take on without having to know too much about the other one.
When to use it
Evans's example is the Funds Transfer, moving money between two accounts. Neither account knows the other, and neither is the natural owner of the operation; the transfer is a domain concept in its own right. Similarly, a pricing engine computes an order's price from pricing rules, the customer segment, the cart, and a coupon, and none of these objects owns the calculation. Credit scoring has the same nature: the answer to “is this customer eligible for loan X?” emerges from a combination of several factors.
The fourth typical case is a coordinator of two aggregates – an operation over two aggregates, neither of which may know the other's details. If it changes both, it runs into the “one aggregate per transaction” rule (see the note after the example below).
When not to use it
Domain Service is the most frequently misused pattern in DDD. Developers used to classic layered architecture reflexively create OrderService, CustomerService, and InvoiceService, move the logic out of the entities into them, and produce an anemic domain model.
Before a Domain Service is created, go through three questions:
- Does this operation naturally belong to some entity? (= it is behavior over a single identity, and the aggregate can perform it without outside help) – if so, it does not belong in a Domain Service.
- Is it really a domain operation, or an application one? A Domain Service contains domain rules. An Application Service coordinates (transactions, authorization, events). If your “domain” service would have to call
EntityManager->flush(), it is an Application Service. - Is it rather an infrastructure detail? Sending an email, hashing a password, reading from an external API – these are not domain operations but infrastructure.
Example: MoneyTransferService
A bank transfer from a source account to a target account. The logic belongs neither in $from (it does not know $to) nor in $to (it does not know $from); it is a domain operation without a natural owner:
1<?php2 3declare(strict_types=1);4 5namespace App\Banking\Domain\Service;6 7use App\Banking\Domain\Account;8use App\Banking\Domain\Exception\InsufficientFundsException;9use App\Banking\Domain\TransferReference;10use App\SharedKernel\Domain\Money;11 12/**13 * Domain Service – transferring money between two accounts.14 *15 * The operation belongs to neither account, because one of them must not know16 * the other: aggregates are autonomous. This is domain logic (validating17 * available funds, checking the limit), not application coordination.18 *19 * Stateless – it holds nothing between calls and changes only the aggregates it receives.20 */21final class MoneyTransferService22{23 public function transfer(24 Account $from,25 Account $to,26 Money $amount,27 TransferReference $reference,28 \DateTimeImmutable $when,29 ): void {30 if (!$from->canWithdraw($amount, $when)) {31 throw InsufficientFundsException::onAccount($from->id(), $amount);32 }33 34 if ($from->currency() !== $to->currency()) {35 // A bare \DomainException is a shortcut; a real project uses a named exception.36 throw new \DomainException(37 'Currency mismatch – use FxTransferService for cross-currency transfers.',38 );39 }40 41 $from->withdraw($amount, $reference, $when);42 $to->deposit($amount, $reference, $when);43 }44}
You can recognize a “real” Domain Service by three traits:
- No state – the class keeps nothing of its own between calls. It works with the objects it receives as parameters.
- No persistence calls –
$from->withdraw()and$to->deposit()mutate the state of the aggregates, but saving them is left to the Application Service or command handler. A Domain Service never calls$em->flush(). - It throws domain exceptions –
InsufficientFundsException, or a bare\DomainExceptionas an acknowledged shortcut – not\RuntimeExceptionor HTTP status codes.
The example follows Evans's account: the service changes both accounts, and the handler that calls it saves them in one transaction. The Aggregate Design chapter presents the same transfer as an anti-pattern because it breaks the “one aggregate per transaction” rule. It holds up where the team deliberately chooses one of the exceptions described in the section When to break the rule. Otherwise, the domain service keeps only the decision (sufficient funds, matching currencies), and a saga splits the transfer itself into two transactions.
The first trait is often tightened into “a domain service must not have a repository in its constructor.” As a rule, that does not hold up, and the sources disagree on it. Vladimir Khorikov distinguishes between a pure and an impure domain service: the latter reaches into an external system because the domain decision cannot be made without it. Matthias Noback places the repository interface in the Domain layer precisely because domain code is supposed to work with it. Vernon's objection, the one most often cited in this debate, is also aimed at injecting a repository into an aggregate, not into a service.
The practical guideline is therefore not a ban. Before a service gets a repository, it pays to consider whether the caller should supply the data instead. A service that loads its own data takes over a piece of orchestration, and its test stops being a pure unit test. When the data cannot be obtained any other way, typically for a rule over an entire collection, a dependency on a domain interface is acceptable and the service stays domain-level. What decides is whether the class contains a domain rule, not the number of its constructor parameters.
Domain Service vs. Application Service vs. Infrastructure Service
Almost every codebase has classes with the Service suffix. What sets them apart is which of the three roles they fill. The table sums up the differences worth asking about in code review:
| Aspect | Domain Service | Application Service | Infrastructure Service |
|---|---|---|---|
| Purpose | Domain logic without a natural owner | Use case coordination (transactions, authorization, events) | Technical integration (DB, email, external API) |
| Layer | Domain | Application | Infrastructure |
| Dependencies | Domain types and domain interfaces (entities, VOs, other Domain Services) | Repositories, Event Bus, Domain Services, Authorization | HTTP clients, libraries (Mailer, Stripe SDK), filesystem |
| State | Stateless | Stateless (one-off handler) | Often stateless, but may hold a connection pool |
| Calls persistence? | No | Yes (through a repository) | Only a persistence adapter (Doctrine repository); not a Mailer or payment gateway |
| Throws exceptions | Domain (InsufficientFundsException) |
Application (UnauthorizedException, validation) |
Infrastructure (ConnectionException) |
| Example name | MoneyTransferService, PricingService |
PlaceOrderHandler, RegisterUserHandler |
SymfonyMailer, StripePaymentGateway |
| Test | Pure unit, without the Symfony kernel | Unit with in-memory fake repositories | Integration (contract with the real system) |
| PHP suffix | *Service (optional) |
*Handler, *UseCase |
*Gateway, *Adapter, *Client |
A uniform *Service suffix erases the difference between the three roles in the table. In practice, the Application layer therefore uses *Handler or *UseCase. A domain service carries the Service suffix only when it emphasizes “an operation without an owner”; often a plain domain name without a suffix is better (FundsTransfer, PricingEngine).
Related topics: DDD Building Blocks – Domain Services, Anti-pattern: Anemic Domain Model, CQRS – Application Handler.
Citations: Evans, E., Domain-Driven Design (2003), chapter 5, A Model Expressed in Software; Vernon, V., Implementing Domain-Driven Design (2013), chapter 7.
08.04 Factories#
Named constructors and reconstitution already appear in DDD Building Blocks as part of the discussion of aggregates. Here they are treated as a pattern of their own: when a static method is enough, when a separate class is needed, and where such a class belongs in the module structure.
What it is
In DDD terminology, a Factory encapsulates complex creation logic for an aggregate or value object where a constructor is not enough. In chapter 6 of Domain-Driven Design (2003), Eric Evans recommends moving the responsibility for creating complex objects and aggregates to a separate object, especially when creation involves rules or polymorphism.
For most aggregates, the constructor is enough. A Factory is useful when:
- Creating the aggregate requires validation that cannot be done only after construction (e.g., “an order placed together with its items (
placePhysical()below) must have at least one, otherwise it is not created”). - Creation is polymorphic – different inputs produce different subtypes of the same aggregate (for example,
Order::placePhysical()vs.Order::placeDigital()). - Creation requires an external lookup – a raw email arrives from a REST API, and the Factory converts it to a
CustomerIdthroughCustomerLookup. - Mapping from a DTO or raw payload is so convoluted that it would clutter the domain object's constructor with transport-layer details.
When not to use it
A Factory does not pay off where the constructor stays clear:
- Trivial creation – an
OrderFactory::create($cust, $items)that internally callsnew Order(...)and nothing else. That is not a Factory; it is a redundant layer. - Service Locator pattern –
$factory->create('Order', [...])deciding based on a string. Type safety is lost. - A Factory for every object in the domain – over-engineering. A Factory is created when needed, not across the board.
Pattern 1: static method factory (preferred)
In PHP 8.4, a factory most often takes the form of a static named creation method on the aggregate itself (a named constructor). The constructor is private, and only named entry points with domain meaning lead out:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Model;6 7use App\Ordering\Domain\Event\OrderPlaced;8use App\Ordering\Domain\Exception\EmptyOrderException;9use App\SharedKernel\Domain\AggregateRoot;10use App\Ordering\Domain\ValueObject\CustomerId;11use App\Ordering\Domain\ValueObject\OrderId;12 13final class Order extends AggregateRoot14{15 /** @var list<OrderItem> */16 private array $items;17 18 /** @param list<OrderItem> $items */19 private function __construct(20 public readonly OrderId $id,21 public readonly CustomerId $customerId,22 array $items,23 private readonly OrderType $type,24 // Here, the time the order was created. In the canonical model from Aggregate Design,25 // placedAt holds the confirmation time and is set only by confirm().26 private readonly \DateTimeImmutable $placedAt,27 ) {28 $this->items = $items;29 // The constructor only fills state. Events are recorded by the factory methods –30 // reconstitute() also goes through the constructor, and it must not raise any event.31 }32 33 // A factory alongside the canonical Order::place(OrderId, CustomerId). It takes34 // the list of items right away so the invariant holds from creation. The canonical35 // placeWithItems() with primitive rows is in the outbox chapter.36 /**37 * Creating an order with physical goods – the counterpart of placeDigital() below.38 *39 * @param list<OrderItem> $items40 */41 public static function placePhysical(42 CustomerId $customerId,43 array $items,44 \DateTimeImmutable $placedAt,45 ): self {46 if (count($items) === 0) {47 throw EmptyOrderException::cannotBePlaced();48 }49 50 $order = new self(51 id: OrderId::generate(),52 customerId: $customerId,53 items: $items,54 type: OrderType::Physical,55 placedAt: $placedAt,56 );57 $order->record(new OrderPlaced($order->id, $customerId));58 59 return $order;60 }61 62 /**63 * Polymorphic creation – digital content only, different rules64 * (no shipping address, instant delivery).65 *66 * @param list<DigitalItem> $items67 */68 public static function placeDigital(69 CustomerId $customerId,70 array $items,71 \DateTimeImmutable $placedAt,72 ): self {73 if (count($items) === 0) {74 throw EmptyOrderException::cannotBePlaced();75 }76 77 $order = new self(78 id: OrderId::generate(),79 customerId: $customerId,80 items: array_map(static fn (DigitalItem $i): OrderItem => $i->toOrderItem(), $items),81 type: OrderType::Digital,82 placedAt: $placedAt,83 );84 $order->record(new OrderPlaced($order->id, $customerId));85 86 return $order;87 }88 89 /**90 * Creation from an import – different validation; the customer is identified not by91 * CustomerId but by an external key, which is bound internally to a guest CustomerId.92 */93 public static function fromImport(94 ImportedOrderRow $row,95 CustomerLookup $lookup,96 \DateTimeImmutable $placedAt,97 ): self {98 $customerId = $lookup->byEmail($row->customerEmail) ?? $lookup->guestId();99 $items = ImportedItems::map($row->items);100 101 return self::placePhysical($customerId, $items, $placedAt);102 }103}
The placePhysical() signature takes the list of items right away to show the invariant “an order without items is not created” enforced at creation. The canonical Order in this book adds items through addItem(ProductId $productId, int $quantity, Money $unitPrice) and allows an empty order; the invariant is then guarded by confirm(). The canonical factory placeWithItems(CustomerId $customerId, array $items) with primitive rows, introduced in the Outbox Pattern chapter, takes the same route: it adds the items through addItem() and confirms the order right away. Both variants are defensible; choosing between them decides whether the aggregate may exist in the Draft state.
Three advantages of a static method factory over a separate Factory class:
- A domain name.
Order::place()orOrder::placeDigital()carries semantics thatnew Order(...)lacks. - A private constructor. No code outside the aggregate can create an
Orderby a path that bypasses validation. The language guards the invariant, not discipline. - Several creation paths without inheritance.
Order::placeDigital()andOrder::fromImport()have different inputs and different rules, but the output is the same type.
Pattern 2: Factory class (when you need DI)
A static method stops being enough when creating the aggregate needs injected dependencies (repositories, external services, configuration). The caller can pass a single service as a parameter, as fromImport() does with CustomerLookup. Once there are three dependencies, though, and every caller would have to obtain them on its own, a separate Factory class supplied with them by the container is clearer:
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Factory;6 7use App\Ordering\Domain\Cart\CartId;8use App\Ordering\Domain\Cart\CartRepository;9use App\Ordering\Domain\Model\Order;10use App\Ordering\Domain\Service\PricingService;11use App\Ordering\Domain\ValueObject\CustomerId;12use Psr\Clock\ClockInterface;13 14/**15 * Factory class – creating an order from a cart requires16 * loading the cart and applying current pricing.17 * The container supplies the dependencies; callers do not have to obtain them.18 */19final class OrderFromCartFactory20{21 public function __construct(22 private readonly CartRepository $carts,23 private readonly PricingService $pricing,24 private readonly ClockInterface $clock,25 ) {}26 27 public function fromCart(CartId $cartId, CustomerId $customer): Order28 {29 $cart = $this->carts->get($cartId);30 31 if ($cart->isEmpty()) {32 // Shortcut: a real project uses a named exception, e.g., EmptyCartException.33 throw new \DomainException('Cannot place order from empty cart.');34 }35 36 $pricedItems = $this->pricing->priceItems($cart->items(), $customer);37 38 return Order::placePhysical(39 customerId: $customer,40 items: $pricedItems,41 placedAt: $this->clock->now(),42 );43 }44}
The Factory class calls Order::placePhysical() internally. It does not take over the “at least 1 item” invariant, which stays in the aggregate's named constructor. The Factory deals only with assembling the input data.
The trio CartRepository, PricingService, and ClockInterface in the constructor looks like a contradiction of section 08.03, where a repository in a service's constructor required justification. The DDD Reference resolves it: a factory itself need not have any responsibility in the model, and yet it is part of the domain design. It does not model a domain concept; it only assembles an aggregate according to domain rules. That is why it may reach for a repository and still stay in Domain/Factory/. The boundary moves elsewhere: as soon as the factory started saving the result or publishing an event, it would become a command handler.
Reconstitution: a special case of Factory
The third type of factory is reconstitution – restoring an aggregate from persistence. With Doctrine, the hydrator takes care of it. Event Sourcing or a custom mapper, however, needs a factory that does not check invariants, because the restored state already passed validation when it was created:
1/**2 * Reconstitution from state loaded from the DB / event stream.3 * This named constructor does not check invariants –4 * the restored state is valid by definition, otherwise it would not have reached persistence.5 *6 * @internal May be called only by the repository infrastructure.7 *8 * @param list<OrderItem> $items9 */10public static function reconstitute(11 OrderId $id,12 CustomerId $customerId,13 array $items,14 OrderType $type,15 \DateTimeImmutable $placedAt,16): self {17 return new self($id, $customerId, $items, $type, $placedAt);18}
That is also why OrderPlaced is recorded by the factory methods (::place(), ::placePhysical()), not by the constructor. Reconstitution must have no side effects: it restores state, and no domain event has happened. Doctrine bypasses the constructor during hydration, but ::reconstitute() above does call it. If the constructor recorded the event, every load of the aggregate through a custom mapper or from an event stream would produce OrderPlaced again, and subscribers would “place” the same order on every read.
The name ::reconstitute() and the @internal PHPDoc tag signal that this creation path is reserved for infrastructure. A command handler calling it instead of ::place() would bypass the aggregate's invariants.
For details: Evans, E., Domain-Driven Design (2003), chapter 6, The Life Cycle of a Domain Object; Vernon, V., Implementing Domain-Driven Design (2013), chapter 11, Factories; Verraes, M., Named Constructors in PHP (2014). Related chapters: DDD Building Blocks – Aggregates, Event Sourcing (reconstitution from an event stream).
08.05 Modules#
What it is
In Evans's terminology, a Module is a deliberate division of code into packages named according to the Ubiquitous Language. The namespace is only a tool; the substance of the pattern is the principle that the package structure reflects the domain language, not technical layers or the libraries in use. Evans devotes a separate passage to it in chapter 5 of Domain-Driven Design (2003) and sees modules as an expression of the model's coarser structure.
The DDD Reference puts it more sharply. A module is part of the model, its name belongs to the Ubiquitous Language, and it should contain a cohesive set of concepts. This has a consequence that practice tends to skip: if modularity does not lead to low coupling between modules, the remedy is to change the model, not to tighten the rules in phparkitect. High coupling between modules is a finding about the domain, not about the tool's configuration.
In Symfony 8 and PHP 8.4, this concretely means:
- PSR-4 namespaces + folder layout according to Bounded Contexts. The default mapping of
App\tosrc/is enough for that; see PSR-4, autoload, and services.yaml. - A published module interface, that is, a narrow set of types through which the outside world enters it.
- Architecture testing, which checks that no code in
App\Billing\reaches directly intoApp\Ordering\.
Module as a Bounded Context
Most often the pattern is applied as 1 module = 1 Bounded Context:
1src/2 Ordering/ ← MODULE = Bounded Context3 Domain/4 Model/5 Order.php ← Aggregate Root6 OrderItem.php7 Repository/8 OrderRepository.php ← Interface9 Specification/10 EligibleForFreeShipping.php11 InEUCountry.php12 Service/13 PricingService.php ← Domain Service14 Factory/15 OrderFromCartFactory.php16 Event/17 OrderPlaced.php18 Exception/19 EmptyOrderException.php20 Application/21 Command/22 PlaceOrder.php23 Handler/24 PlaceOrderHandler.php25 Query/26 ListOrders.php27 ListOrdersHandler.php28 Infrastructure/29 Repository/30 DoctrineOrderRepository.php31 Doctrine/32 Type/OrderIdType.php33 Http/34 OrderController.php35 Messenger/36 OrderPlacedSubscriber.php37 Billing/ ← Another BC = another module38 Domain/39 Invoice.php40 ...41 Application/42 ...43 Infrastructure/44 ...45 SharedKernel/ ← Shared language and types46 Domain/47 Money.php48 Currency.php49 Country.php50 AggregateRoot.php51 Specification/52 Specification.php53 CompositeSpecification.php54 AndSpecification.php55 OrSpecification.php56 NotSpecification.php57 QuerySpecification.php
The related division by feature is covered in the section Vertical Slice Architecture. For this chapter, one observation is enough: the top level of directories shows the project's domain map (Ordering, Billing, SharedKernel), not technical folders like Twig/Doctrine/Service.
Anti-pattern: type packaging
PSR-4, autoload, and services.yaml
A widespread belief is that a modular structure requires a separate PSR-4 root for each module. It does not. PSR-4 maps a namespace prefix to a base directory and translates the rest of the namespace into subdirectories. With Symfony's default mapping "App\\": "src/", the class App\Ordering\Domain\Model\Order is therefore looked up in src/Ordering/Domain/Model/Order.php – exactly where the modular structure puts it. You do not have to touch composer.json, and the structure from the previous example works without a single change.
A separate root per module makes sense in two situations. Either the modules do not sit under src/, or a module is meant to become a standalone Composer package with its own composer.json over time. The configuration then looks like this:
1{2 "autoload": {3 "psr-4": {4 "App\\Ordering\\": "modules/ordering/src/",5 "App\\Billing\\": "modules/billing/src/",6 "App\\SharedKernel\\": "src/SharedKernel/"7 }8 }9}
After such a change, run composer dump-autoload.
A similar myth persists around config/services.yaml. The default configuration registers App\ with resource: '../src/', so services inside modules are autoregistered on their own. A controller extending AbstractController gets the controller.service_arguments tag from autoconfigure: true, so it does not need to be listed either. Listing services per module is therefore a choice, not a necessity.
It pays off when you set different _defaults for modules, or when you want to exclude the domain layer from the container:
1services:2 _defaults:3 autowire: true4 autoconfigure: true5 6 App\:7 resource: '../src/'8 exclude:9 - '../src/*/Domain/'10 - '../src/SharedKernel/Domain/'11 12 # Domain services and factory classes belong in the container; the rest of the domain layer does not.13 App\Ordering\Domain\Service\:14 resource: '../src/Ordering/Domain/Service/'15 16 App\Ordering\Domain\Factory\:17 resource: '../src/Ordering/Domain/Factory/'
The exclusion keeps aggregates, value objects, and specifications out of the container. Nobody injects them; anyone who did would be mishandling them. Domain services and factory classes such as OrderFromCartFactory are registered separately, because those do get injected.
An excluded directory, however, also drops out of automatic interface aliasing. Ports such as OrderRepository live right there, so their alias to the implementation has to be written by hand – the chapter on architectural styles covers this.
The module contract
Evans's Module from 2003 rests on cohesion of concepts and low coupling between modules. Today's practice under the heading of the modular monolith adds a third requirement. Kamil Grzybek describes a module as a vertical slice of the business with three properties: independence and interchangeability, completeness (it contains everything the feature needs), and a well-defined interface through which the module is entered.
The third property is a shift compared to 2003. Forbidding foreign imports is not enough; the module should expose a narrow set of types that the outside world may call and keep the rest internal. In practice, this means an Ordering/PublicApi/ folder with command and query interfaces plus published events, and an architecture rule that another module may import only from there. Compared to a mere import ban, refactoring inside the module then affects nobody else, because it touches nothing the neighbor can see.
The modular monolith as a whole is covered in the chapter DDD and Microservices: when it pays off, how to move away from it later, and what rules to set for it.
Architecture testing: boundaries enforced in CI
Convention alone is not enough – developers under pressure forget that App\Billing\ must not call App\Ordering\. The rule is therefore enforced by a test that runs in CI and breaks the build on a violation. The principle is the same for every tool: dependency rules live as versioned definitions next to the code, and the pipeline checks them on every commit. For the modular project in this chapter, there are typically three rules:
App\Orderingmust not depend onApp\Billing,App\Inventory, orApp\Shipping– integration between BCs happens exclusively through integration events (Outbox). The exceptions are identifiers of other contexts (App\*\Domain\ValueObject\*Id): an aggregate refers to another aggregate precisely through its ID (Aggregate Design).App\Ordering\Domainmust not import anything fromSymfony, from the runtime part of Doctrine ORM (EntityManager,QueryBuilder), or from its own Application and Infrastructure layers. There are three deliberate exceptions. TheSymfony\Component\Uidcomponent generates identifiers (Uuid::v7()). The book puts theDoctrine\ORM\Mappingmapping attributes directly on domain classes (see the mapping choice). The aggregate's collections and theCriteriain specifications are built on thedoctrine/collectionslibrary.App\Ordering\Applicationmust not knowApp\Ordering\Infrastructure– orchestration depends on an interface from Domain, not on the adapter.
PHP has two established tools. phparkitect expresses rules as PHP definitions (a fluent API over a set of classes) in a phparkitect.php file at the project root:
1composer require --dev phparkitect/phparkitect2vendor/bin/phparkitect check
In an established project, the tool is introduced through a baseline. Violations from the generated list do not break the build, so the rules apply immediately and the old debt is paid down gradually. Without a baseline, the first run ends with hundreds of errors and the team switches the tool off.
The second option is Deptrac, which describes layers and allowed dependencies in a configuration file. A complete Deptrac configuration for a DDD project, including the CI setup, is in the chapter Testing DDD. The way rules are written differs between the tools; both can express the three rules above.
Related: Vertical Slice Architecture (and horizontal vs. vertical splitting), Bounded Context and Context Mapping, Implementation in Symfony 8, Outbox Pattern (communication between modules through events).
Citations: Evans, E., Domain-Driven Design (2003), chapter 5, A Model Expressed in Software, section Modules; Vernon, V., Implementing Domain-Driven Design (2013), chapter 9, Modules; phparkitect documentation, github.com/phparkitect/arkitect.
08.06 How these patterns relate to the rest of DDD#
The table sums up how the four patterns of this chapter relate to the aggregate, the domain event, and the Bounded Context:
| Pattern | Relation to Aggregate | Relation to Domain Event | Relation to Bounded Context |
|---|---|---|---|
| Specification | Validates an aggregate invariant or filters a list of aggregates | A rule that triggers an event (e.g., OrderQualifiedForFreeShipping) | The rule lives inside the BC; only the pattern skeleton is shared in the SharedKernel |
| Domain Service | Coordinates 2+ aggregates without linking them by a dependency | Calls aggregates, which then emit events | Lives inside the BC; cross-BC coordination belongs in an Application Service / saga |
| Factory | Creates an aggregate with a validated initial state | Usually records the first event on creation (OrderPlaced) | Lives inside the BC; there is no Factory for cross-BC objects |
| Module | Groups all aggregates of a BC into one package | Defines the boundary that events cross (Outbox) | 1 module = 1 BC (the preferred application) |
The last column for Specification needs an explanation. The pattern skeleton (the interface, CompositeSpecification, and the three combinators) is shared by all contexts through SharedKernel. The concrete rule EligibleForFreeShipping, by contrast, belongs to one context and would mean nothing elsewhere. The mechanism is shared, not the rule.
Internally, an aggregate uses specifications for invariants, comes into being through a factory (a named constructor), and collaborates with other aggregates through a domain service. The whole group lives in one module, which corresponds to a Bounded Context.
08.07 Anti-patterns summary#
A quick reference for code review. The remedy for each anti-pattern is discussed in the corresponding section above.
| Anti-pattern | Symptom | Remedy |
|---|---|---|
| Specification as a 1-line if | OrderTotalGreaterThanSpecification with a single comparison |
Inline the condition; a Specification should represent a whole domain question |
| Specification reimplementing SQL | The specification has two independent versions of the rule – one in PHP, the other in DQL, each somewhere else | Keep both forms in one class (QuerySpecification) and secure them with a contract test |
| “*Service” everywhere | OrderService, CustomerService contain domain logic that the entity should contain |
Move the logic into the entity; Domain Service only for operations without an owner |
| Application Service posing as a Domain Service | The domain Service has EntityManager in its constructor and calls flush() |
Split it into a Domain Service (logic) + Application Handler (orchestration) |
| Factory for every object | Every class in the domain has a separate Factory class | Static method (named constructor) on the aggregate; a Factory class only if you really need DI |
| Public aggregate constructor | new Order(...) can be called outside the aggregate, bypassing validation |
Private constructor + ::place() / ::reconstitute() |
Type packaging (src/Entity/, src/Service/) |
The directory structure shows technology, not the domain | Switch to 1 module = 1 BC; enforce it with phparkitect |
| Modules without architecture tests | Conventions exist, but nobody checks them – erosion at the first hot-fix pressure | Put phparkitect/deptrac into CI from the first commit |
| Cross-BC import without an ACL | App\Billing\Invoice directly imports App\Ordering\Order |
Integration through integration events (Outbox); a mapper to a local type in the target BC |
Domain anti-patterns – the anemic model, transaction script, and “Big Ball of Mud” – are covered in detail in the chapter Anti-Patterns and Common Mistakes.
08.08 Summary#
Specifications, Domain Services, Factories, and Modules are four patterns from Evans's tactical catalog that practical guides leave out. Without them, aggregates bloat, the domain model grows thin, and the project structure obscures the domain.
- Specification Pattern turns boolean domain rules into first-class objects with descriptive names. The combinators
and,or, andnotcompose rules without nestedifs, and theQuerySpecificationinterface keeps both the PHP and the query form of a rule (DoctrineCriteria) in one class. - Domain Services capture domain logic that belongs to no entity or value object. They are stateless, live in the Domain layer, and do not call persistence. When they are confused with Application or Infrastructure Services, logic drains out of the entities and the model turns anemic.
- Factories handle complex aggregate creation. The preferred form is a named constructor (a static method on the aggregate) with a private constructor. A separate Factory class comes into play only when you need DI dependencies.
- Modules organize code according to the Ubiquitous Language, not according to technical layers. In Symfony 8, the default PSR-4 mapping of
App\tosrc/is enough. The real cost lies in the published module interface and in enforcing the boundaries in CI with phparkitect or deptrac.
The list of skipped patterns does not end there. Evans's Supple Design chapter contains eight more patterns: Intention-Revealing Interfaces, Side-Effect-Free Functions, Assertions, Standalone Classes, Closure of Operations, Declarative Design, Drawing on Established Formalisms, and Conceptual Contours. The book does not cover them systematically, because they are patterns at the level of individual methods and signatures, not building blocks of the model. They are the natural next reading for going deeper into tactical design.
Together, the four patterns of the chapter keep the aggregate at a reasonable size, the domain separate from infrastructure, and the project readable even after a year of development. They are introduced gradually. For the first iteration, 1 module = 1 BC, a named constructor for the 2–3 main aggregates, and a Domain Service wherever there used to be an owner-less “*Service” are enough. Specifications pay off once a second or third combination of the same rule appears.
How aggregates behave at thousands of transactions per second, where DDD has overhead, and how to minimize it is shown in the chapter Read Models, Projections, and Performance. The chapter Anti-Patterns and Common Mistakes adds detail on the anemic model, which section 08.03 touched on only briefly.
Frequently asked questions
When exactly does the Specification Pattern pay off?
It pays off when you need the same or a related rule in at least two places, or when you apply it both in the domain and in the repository through QuerySpecification. A rule used once and one line long does not need a separate class; it belongs inline. The main test: does the rule have a domain name that the team uses in discussions (premium customer, eligible for free shipping)? If so, a Specification gives that name code. A class named OrderTotalGreaterThanSpec is only an operator and belongs back in an inline if. Details in the Specification – When to use it section.
Should a Domain Service have state?
No. A Domain Service is stateless by definition – no instance variables that change between calls, no internal cache, no counter. With state, predictability (the result depends on earlier calls) and safety under concurrency are lost. Dependencies, however, are a different topic from state, and the answer there is not categorical: a Mailer or an HTTP client really does push the service into the Application or Infrastructure layer, while on repositories the sources disagree. Khorikov allows an impure domain service, and Noback places the repository interface directly in the Domain layer. The guideline: first consider whether the caller should supply the data; when you cannot get it any other way, a dependency on a domain interface is acceptable. Details in the Example: MoneyTransferService section and the comparison table.
Factory method or Factory class – how to decide?
The default choice is a named constructor (a static method on the aggregate). In chapter 11, Factories, Vernon (2013) puts the factory method on the aggregate root first and treats a separate factory only as the second option, at the service level. Mathias Verraes described the PHP form with a private constructor in Named Constructors in PHP (2014). A separate Factory class comes into play when creating the aggregate requires DI dependencies – typically CartRepository, PricingService, ClockInterface, or an external lookup. A single service can be passed to a static method as a parameter, but with several dependencies every caller would have to obtain them. A Factory class without a single DI dependency that only calls new Order(...) is a redundant layer and should be deleted. Details in the Pattern 2: Factory class section.
How do you enforce boundaries between Modules in a PHP project?
Convention alone does not last – a developer under “do it fast” pressure adds a cross-BC import in five minutes. Reliable enforcement requires a tool in CI: phparkitect or deptrac. Rules such as “App\Ordering must not depend on App\Billing” or “App\Ordering\Domain must not call EntityManager” break the CI build on a violation. It costs one configuration file, and the modular organization survives even the fifth new developer. Details in the Architecture testing section.
What should the namespace of a class that sits on the boundary of two Bounded Contexts look like?
In clean DDD, no class sits on the boundary of two BCs. Such a case signals that the boundary is drawn wrong or that you need an Anti-Corruption Layer (ACL). The concrete solution: each BC has its own type with its own namespace. App\Ordering\Domain\ValueObject\CustomerId in the Ordering context, App\Billing\Domain\ValueObject\CustomerId in the Billing context, or mapping through events. If a truly universal concept exists (Money, Currency, Country), it belongs in the SharedKernel – but that package must be deliberately small, stable, and agreed on by all teams. Related: Module as a Bounded Context.
Can Specification and Domain Service be combined?
Yes, in practice they are combined often. A Domain Service usually coordinates 2+ aggregates, and one of the decisions along the way is carried by a Specification – typically “can this order proceed to shipping?” = the composition HasBeenPaid AND ItemsInStock AND NotInBlacklist. The Domain Service instantiates that specification, calls isSatisfiedBy(), and depending on the result calls a method on the aggregate. The patterns complement each other: the Specification is the rule, and the Domain Service is the action that applies the rule to 2+ aggregates. Details in the How these patterns relate to the rest of DDD section.