Chapter 24 · Synthesis · Case Study

Case Study

One project from start to finish: a project management system in Symfony 8. Domain analysis, finding the Bounded Contexts, strategic and tactical design, and an implementation with CQRS.

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

24.01 Introduction#

Illustrative scenario: the team, the numbers, and the decisions in this chapter are fictional. They serve as one continuous demonstration of DDD and CQRS in a single project.

A team got the assignment to build a project management system. Users create projects, add tasks, assign them to team members, change their status, and comment on them. The assignment looks trivial, and a developer's first instinct is a projects table, a tasks table with a foreign key, a comments table, and a TaskService that handles it all. Three months later, TaskService has eight hundred lines, and every change to task assignment breaks reporting. This study shows the other path: strategic and tactical design following DDD, with CQRS in Symfony 8, from the first workshop to projections with reconciliation.

24.02 Requirements#

The project management system has the following requirements:

  • Users can register and sign in.
  • Users can create projects.
  • Users can add tasks to projects.
  • Users can assign tasks to team members.
  • Users can change the status of tasks (To Do, In Progress, Done).
  • Users can add comments to tasks.
  • Users can follow activity on projects and tasks.
  • The system must be scalable and maintainable.

24.03 Domain analysis#

Architecture starts with a conversation with domain experts, not with code. Before any decision about tables and classes, the team has to know what happens in the domain and where the boundaries lie. The five Bounded Contexts in the Architecture section below did not come out of an architect's head. They emerged from three steps of Event Storming: collecting domain events, grouping them into subdomains, and drawing the context boundaries. The format comes from Alberto Brandolini; the notation, the course of the workshop, and its anti-patterns are covered in the chapter Event Storming and Domain Storytelling.

Step 1: collecting domain events

The first workshop looked for an answer to the question “what happens in the system.” The domain experts formulated, in chronological order, the events that matter to them, regardless of the structure of the code, the framework, or the database. The goal is to capture the vocabulary (Ubiquitous Language), not the implementation.

  • A user registered.
  • A user signed in.
  • A user created a project.
  • The project owner invited another user as a member.
  • The invited user accepted the project invitation.
  • The project owner removed a member.
  • A project member added a task.
  • The owner assigned a task to a member.
  • The assigned member took over the task (status To Do → In Progress).
  • The assigned member completed the task (In Progress → Done).
  • A project member added a comment to a task.
  • The comment's author edited the comment.
  • The system recorded the activity for the audit.

The event vocabulary brought an important finding before any code existed. The word “user” has a different meaning in each context: in UserManagement it is an identity with an email and a password, in ProjectManagement it is an owner or a member, in TaskManagement the assignee, and in CommentManagement the author of a text. The split into Bounded Contexts grew out of this finding.

Step 2: grouping events into subdomains

On the second day, the team clustered the events by meaning. For each group, the question was who on the business side is responsible for it. A group that a single expert understands is a candidate for a subdomain. The result was a map of events to subdomains:

Subdomain Event Domain expert
UserManagement UserRegistered Security administrator
UserManagement UserSignedIn Security administrator
ProjectManagement ProjectCreated Project manager
ProjectManagement MemberAdded Project manager
ProjectManagement MemberRemoved Project manager
TaskManagement TaskCreated Team lead
TaskManagement TaskAssigned Team lead
TaskManagement TaskStatusChanged Team lead
CommentManagement CommentAdded Team lead
CommentManagement CommentEdited Team lead
ActivityTracking ActivityRecorded Compliance / internal audit

The Domain expert column helps verify that the context boundaries match the organizational reality. A context that needs four different experts is probably gluing together unrelated responsibilities. If, on the other hand, the same expert drives two contexts, they are candidates for merging – or the expert covers more roles than is healthy.

Classifying the subdomains

Five subdomains do not mean five equally important parts of the system. Before turning them into contexts, the team placed each of them into one of the three categories from the chapter Subdomains: Core, Supporting, Generic. The classification decides how much modeling each part deserves.

Subdomain Category Consequence for the design
ProjectManagement Core its own model, rich invariants, the most workshop time
TaskManagement Core the task's state machine is what sets the product apart
CommentManagement Supporting a small model, no extra investment in tactical patterns
ActivityTracking Supporting an append-only log without invariants
UserManagement Generic registration, sign-in, password reset – a solved problem

Classifying UserManagement as Generic goes against the first instinct to build custom authentication. What such a choice costs is shown in Illustrative scenario: custom auth as a budget trap. The context stays in the study because it carries a boundary and a relationship in the Context Map. Its model, however, is thin: an identity, an email, and delegation to Symfony Security or to an external identity provider. The domain work concentrates in the two Core contexts.

Without this step, every context gets the same investment in its model, which is the anti-pattern “everything is Core”.

Step 3: defining the context boundaries

The third step turned the subdomains into Bounded Contexts, that is, units in which the vocabulary has one meaning, the model one set of invariants, and the code one module boundary. There were three criteria for a boundary:

  1. Semantic coherence – words inside the context have one meaning. If “status” means the state of a task in one place and the state of a project in another, that is a signal to split.
  2. Domain ownership – each context has one domain expert responsible for its rules and vocabulary. Without an identifiable owner, decisions about the model are random.
  3. Pace of change – parts of the system that change together belong in the same context. If a change in TaskManagement repeatedly forces a change in CommentManagement, the boundary between them is drawn in the wrong place.

The mapping came out 1:1: each subdomain produced exactly one context. That is the default goal, not an automatic result. Splitting a subdomain into several contexts pays off only for operational reasons, such as separate development cycles. The opposite case is more common: several small Supporting and Generic subdomains fit into one context (Mapping subdomains to Bounded Contexts).

In this project, all three criteria pointed the same way. The only opposing signal came from step 2: TaskManagement and CommentManagement are driven by the same team lead, which made them candidates for merging. The team kept them separate for the sake of semantic coherence: a “user” is the assignee in one context and the author of a text in the other. The complete map of relationships between the contexts (Partnership, Customer/Supplier, Open Host Service) is in the Architecture section. A deeper theoretical basis for identifying contexts is provided by the chapters What Is Domain-Driven Design and DDD Building Blocks.

24.04 Architecture#

The strategic level holds five Bounded Contexts and a Context Map of their relationships; the relationship types the map uses are introduced in the chapter Bounded Context and Context Mapping. The tactical level is home to aggregates, value objects, domain events, and domain services. The code is organized into vertical slices: each feature contains everything from the command to the view model. A change in task assignment does not show up in reporting, because the two live in different slices and communicate through explicit contracts.

Strategic design: Bounded Contexts and Context Map

The domain analysis in section 24.03 produced five contexts:

  • UserManagement – identity, registration, authentication; the owner of users' access rights.
  • ProjectManagement – the lifecycle of projects and users' membership in a project.
  • TaskManagement – tasks, their assignment, and their state transitions.
  • CommentManagement – comments and feedback on tasks.
  • ActivityTracking – an audit trail over the events from the other contexts.
FIG. 24.4-A Context Map: relationships between five Bounded Contexts

Relationships captured in the Context Map:

  • UserManagement ⟷ ProjectManagement – Partnership. The models stay separate: UserManagement holds the identity, ProjectManagement the membership in a project. Inviting and accepting a member, however, needs both contexts, so their development is planned and released together.
  • ProjectManagement → TaskManagement – Customer/Supplier. TaskManagement states what contract about a project's existence and membership it needs. When and in what shape it gets delivered is decided by ProjectManagement as the upstream.
  • TaskManagement → CommentManagement – Customer/Supplier. A comment holds a TaskId and loses its meaning without the task, so the contract is supplied by TaskManagement. CommentManagement raises its needs as the downstream, but the upstream decides whether they get delivered. Without this voice, it would be a Conformist.
  • All contexts → ActivityTracking – domain events on a shared bus. The diagram describes this relationship as Open Host Service / Published Language. That is only partly accurate: the published events carry ProjectId, UserId, and TaskStatus, that is, internal types of the publishing context. A Published Language, by contrast, is a separate exchange format thanks to which the consumer depends on the event's schema, not on the publisher's classes. Until a thin integration event with primitives exists, this amounts to publishing the internal model to the outside (Open Host Service, Published Language).
  • Shared identifiers – UserId, ProjectId, and TaskId form a minimal Shared Kernel. In the diagram they stand in their own package; in the code they live in the owning context and the others import them. Evans's condition for the pattern is a commitment to coordinate every change; here a single circumstance upholds it: there is only one team. The cost and the alternative are in section 24.07.2.

Partnership and Customer/Supplier both describe how teams cooperate. Yet the study is developed by a single team, and five contexts are more than one team can carry in the long run according to the cognitive load rule. The study shows the boundaries of the model, not a team topology. The map says how the contexts will cooperate once separate teams take them over.

The boundary between TaskManagement and ProjectManagement is held by a port, not by an Anti-Corruption Layer. Both contexts work with the same ProjectId and UserId classes imported from the owning contexts, so nothing is translated. What remains is dependency inversion: the ProjectChecker port is defined in the TaskManagement domain, and its infrastructure implementation is an adapter into ProjectManagement. It becomes an Anti-Corruption Layer in Evans's sense once the adapter gains a translation between two models, for example when ProjectManagement moves into its own service with its own response shape. The “ACL” label in the diagram therefore names the target state, not the current one. The choice between synchronous and asynchronous integration is discussed in section 24.07.3.

Asynchronous integration between contexts uses domain events published through Symfony Messenger. A concrete example of a projection that listens to events from two contexts is in section 24.06.

Tactical design and project structure

The tactical level rests on entities and value objects. An entity has an identity that survives changes to its attributes (User, Project, Task). For a value object, only the values matter; it has no identity and does not change (UserId, ProjectId, TaskStatus). Four more building blocks stand on top of them. An aggregate holds a group of objects that the domain changes as a single unit; here that is Project and, separately, Task. A domain event records what happened and what matters to the domain experts (ProjectCreated, TaskAssigned). A repository encapsulates the persistence of an aggregate, so the domain code knows nothing about the database. And a domain service carries a rule that belongs to no entity or value object; in this study that is TaskAssignmentService, whose existence is discussed in section 24.07.4.

The directory structure mirrors both the strategic and the tactical design. Each Bounded Context has its own domain layer, infrastructure, and feature slices; shared components live in SharedKernel/:

bash snippet.sh
1src/2├── UserManagement/            # Bounded Context: user management3│   ├── Domain/                # Domain layer4│   │   ├── Model/             # Domain models5│   │   │   └── User.php        # User entity (Aggregate Root)6│   │   ├── ValueObject/       # Value objects7│   │   │   ├── UserId.php8│   │   │   └── Email.php9│   │   ├── Event/             # Domain events10│   │   │   └── UserRegistered.php11│   │   └── Repository/        # Repositories (interfaces)12│   │       └── UserRepository.php13│   ├── Infrastructure/        # Infrastructure layer14│   │   └── Repository/        # Repository implementations15│   │       └── DoctrineUserRepository.php16│   ├── Registration/          # Feature: user registration17│   │   ├── Command/           # Commands18│   │   │   ├── RegisterUser.php19│   │   │   └── RegisterUserHandler.php20│   │   └── Controller/        # Controllers21│   │       └── RegistrationController.php22│   ├── Authentication/        # Feature: authentication23│   │   └── Controller/        # Controllers24│   │       └── SecurityController.php25│   └── GetUser/               # Feature: get a user26│       ├── Query/             # Queries27│       │   ├── GetUser.php28│       │   └── GetUserHandler.php29│       └── ViewModel/         # View models30│           └── UserViewModel.php31├── ProjectManagement/         # Bounded Context: project management32│   ├── Domain/33│   │   ├── Model/34│   │   │   ├── Project.php     # Project entity (Aggregate Root)35│   │   │   └── ProjectMember.php36│   │   ├── ValueObject/37│   │   │   ├── ProjectId.php38│   │   │   └── ProjectStatus.php39│   │   ├── Event/40│   │   │   ├── ProjectCreated.php41│   │   │   ├── MemberAdded.php42│   │   │   └── MemberRemoved.php43│   │   ├── Exception/         # Named domain exceptions44│   │   │   └── ProjectOwnerCannotBeRemovedException.php45│   │   └── Repository/46│   │       └── ProjectRepository.php47│   ├── Infrastructure/48│   │   └── Repository/49│   │       └── DoctrineProjectRepository.php50│   ├── CreateProject/         # Feature: create a project51│   │   ├── Command/52│   │   │   ├── CreateProject.php53│   │   │   └── CreateProjectHandler.php54│   │   └── Controller/55│   │       └── ProjectController.php56│   └── GetProjects/           # Feature: list of projects57│       ├── Query/58│       │   ├── GetProjects.php59│       │   └── GetProjectsHandler.php60│       ├── Controller/61│       │   └── ProjectsController.php62│       └── ViewModel/63│           └── ProjectViewModel.php64├── TaskManagement/            # Bounded Context: task management65│   ├── Domain/66│   │   ├── Model/67│   │   │   └── Task.php        # Task entity (Aggregate Root)68│   │   ├── ValueObject/69│   │   │   ├── TaskId.php70│   │   │   └── TaskStatus.php71│   │   ├── Event/72│   │   │   ├── TaskCreated.php73│   │   │   ├── TaskAssigned.php74│   │   │   └── TaskStatusChanged.php75│   │   ├── Service/           # Domain services76│   │   │   └── TaskAssignmentService.php77│   │   ├── Port/              # Ports to other contexts78│   │   │   └── ProjectChecker.php79│   │   ├── Exception/80│   │   │   ├── AssigneeNotProjectMemberException.php81│   │   │   ├── InvalidTaskStateTransitionException.php82│   │   │   ├── ProjectNotFoundException.php83│   │   │   └── TaskNotFoundException.php84│   │   └── Repository/85│   │       └── TaskRepository.php86│   ├── Infrastructure/87│   │   └── Repository/88│   │       └── DoctrineTaskRepository.php89│   ├── CreateTask/            # Feature: create a task90│   │   ├── Command/91│   │   │   ├── CreateTask.php92│   │   │   └── CreateTaskHandler.php93│   │   └── Controller/94│   │       └── TaskController.php95│   ├── AssignTask/            # Feature: assign a task96│   │   ├── Command/97│   │   │   ├── AssignTask.php98│   │   │   └── AssignTaskHandler.php99│   │   └── Controller/100│   │       └── AssignController.php101│   ├── ChangeStatus/          # Feature: change a task's status102│   │   ├── Command/103│   │   │   ├── ChangeTaskStatus.php104│   │   │   └── ChangeTaskStatusHandler.php105│   │   └── Controller/106│   │       └── StatusController.php107│   └── GetTask/               # Feature: get a task108│       ├── Query/109│       │   ├── GetTask.php110│       │   └── GetTaskHandler.php111│       └── ViewModel/112│           └── TaskViewModel.php113├── CommentManagement/         # Bounded Context: comment management114│   ├── Domain/115│   │   ├── Model/116│   │   │   └── Comment.php117│   │   ├── ValueObject/118│   │   │   └── CommentId.php119│   │   ├── Event/120│   │   │   └── CommentAdded.php121│   │   └── Repository/122│   │       └── CommentRepository.php123│   ├── Infrastructure/124│   │   └── Repository/125│   │       └── DoctrineCommentRepository.php126│   └── AddComment/            # Feature: add a comment127│       ├── Command/128│       │   ├── AddComment.php129│       │   └── AddCommentHandler.php130│       └── Controller/131│           └── CommentController.php132├── ActivityTracking/          # Bounded Context: activity tracking133│   ├── Domain/134│   │   ├── Model/135│   │   │   └── Activity.php136│   │   ├── ValueObject/137│   │   │   └── ActivityId.php138│   │   └── Repository/139│   │       └── ActivityRepository.php140│   ├── Infrastructure/141│   │   └── Repository/142│   │       └── DoctrineActivityRepository.php143│   └── RecordActivity/        # Feature: record an activity144│       ├── Command/145│       │   ├── RecordActivity.php146│       │   └── RecordActivityHandler.php147│       └── Controller/148│           └── ActivityController.php149└── SharedKernel/              # Shared components150    ├── Domain/                # Shared domain logic151    │   ├── AggregateRoot.php  # Aggregate base class (record/releaseEvents)152    │   └── Bus/               # Message bus interfaces153    │       ├── CommandBus.php   # Command bus interface154    │       └── QueryBus.php     # Query bus interface155    └── Infrastructure/        # Shared infrastructure156        ├── Bus/               # Message bus implementations157        │   ├── MessengerCommandBus.php  # Command bus implementation158        │   └── MessengerQueryBus.php  # Query bus implementation159        └── Persistence/        # Shared persistence160            └── DoctrineTypes/    # Custom Doctrine types161                └── UuidType.php    # Type for UUIDs

24.05 Implementation#

Ubiquitous Language

The vocabulary was created with the domain experts at the workshop. The same terms appear in the classes, in conversations with the product manager, and in tickets:

  • Project – An organizational unit that groups related tasks and team members.
  • Task – A unit of work in a project that needs to be completed.
  • Assignee – The team member to whom a task is assigned.
  • Status – The state of a task (To Do, In Progress, Done).
  • Comment – Written feedback on a task.
  • Activity – A record of an action performed in the system.

Domain model: Project (aggregate root)

The aggregate carries Doctrine attributes directly on the domain class, which is the pragmatic default according to the chapter Implementation in Symfony 8. The class extends AggregateRoot (shared behavior for record and releaseEvents, see Aggregates and domain events: the lifecycle) and is final, because an aggregate is not meant to be extended. The constructor is private, and the aggregate comes into being through the static factory method create().

final on a Doctrine entity requires native lazy objects. They are turned on by $config->enableNativeLazyObjects(true) on PHP 8.4; the method arrived in ORM 3.4.0, and since 3.5 the old mode with generated proxies is deprecated. Without them, Doctrine needs a proxy derived from the entity, and final does not get through.

A public readonly identifier, however, is a separate problem that native lazy objects do not solve. find(), persist(), and flush() work, but hydrating an already existing object does not: $em->refresh($project) and the first touch of a reference from $em->getReference() both end with LogicException: Attempting to change readonly property. During rehydration, Doctrine writes the property again, and for a readonly property with an object value it rejects the change, because the newly built ProjectId is not the same instance. A reference from getReference() runs into the identifier, refresh() into every such property, including createdAt. Code that uses getReference() gives the identifier an ordinary private property with a getter, as Task does below; code that keeps readonly objects in an aggregate does not call refresh() on it.

php src/ProjectManagement/Domain/Model/Project.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Domain\Model;6 7use App\ProjectManagement\Domain\Event\MemberAdded;8use App\ProjectManagement\Domain\Event\MemberRemoved;9use App\ProjectManagement\Domain\Event\ProjectCreated;10use App\ProjectManagement\Domain\Exception\ProjectOwnerCannotBeRemovedException;11use App\ProjectManagement\Domain\ValueObject\ProjectId;12use App\SharedKernel\Domain\AggregateRoot;13// UserId lives in UserManagement; the other contexts import it (see section 24.07.2)14use App\UserManagement\Domain\ValueObject\UserId;15use Doctrine\ORM\Mapping as ORM;16 17#[ORM\Entity]18#[ORM\Table(name: 'projects')]19final class Project extends AggregateRoot20{21    #[ORM\Id]22    #[ORM\Column(type: 'project_id')]23    public readonly ProjectId $id;24 25    #[ORM\Column(type: 'string', length: 255)]26    private string $name;27 28    #[ORM\Column(type: 'text', nullable: true)]29    private ?string $description;30 31    #[ORM\Column(type: 'user_id')]32    public readonly UserId $ownerId;33 34    /** @var list<UserId> */35    #[ORM\Column(type: 'user_id_list')]36    private array $memberIds = [];37 38    #[ORM\Column(type: 'datetime_immutable')]39    public readonly \DateTimeImmutable $createdAt;40 41    #[ORM\Column(type: 'datetime_immutable', nullable: true)]42    private ?\DateTimeImmutable $updatedAt = null;43 44    #[ORM\Version]45    #[ORM\Column(type: 'integer')]46    private int $version = 1;47 48    private function __construct(ProjectId $id, string $name, ?string $description, UserId $ownerId)49    {50        $this->id = $id;51        $this->name = $name;52        $this->description = $description;53        $this->ownerId = $ownerId;54        $this->memberIds = [$ownerId];55        $this->createdAt = new \DateTimeImmutable();56    }57 58    public static function create(ProjectId $id, string $name, ?string $description, UserId $ownerId): self59    {60        $project = new self($id, $name, $description, $ownerId);61        $project->record(new ProjectCreated($id, $name, $description, $ownerId));62 63        return $project;64    }65 66    public function name(): string67    {68        return $this->name;69    }70 71    public function description(): ?string72    {73        return $this->description;74    }75 76    /** @return list<UserId> */77    public function memberIds(): array78    {79        return $this->memberIds;80    }81 82    public function addMember(UserId $userId): void83    {84        foreach ($this->memberIds as $existingId) {85            if ($existingId->equals($userId)) {86                return; // already a member – idempotent operation87            }88        }89        $this->memberIds[] = $userId;90        $this->updatedAt = new \DateTimeImmutable();91 92        $this->record(new MemberAdded($this->id, $userId));93    }94 95    public function removeMember(UserId $userId): void96    {97        if ($this->ownerId->equals($userId)) {98            throw ProjectOwnerCannotBeRemovedException::forProject($this->id);99        }100 101        $before = count($this->memberIds);102        $this->memberIds = array_values(array_filter(103            $this->memberIds,104            fn(UserId $id) => !$id->equals($userId),105        ));106 107        if (count($this->memberIds) === $before) {108            return; // was not a member – idempotent operation109        }110 111        $this->updatedAt = new \DateTimeImmutable();112        $this->record(new MemberRemoved($this->id, $userId));113    }114 115    public function rename(string $newName): void116    {117        if ($this->name === $newName) {118            return;119        }120        $this->name = $newName;121        $this->updatedAt = new \DateTimeImmutable();122    }123 124    public function changeDescription(?string $newDescription): void125    {126        if ($this->description === $newDescription) {127            return;128        }129        $this->description = $newDescription;130        $this->updatedAt = new \DateTimeImmutable();131    }132 133    public function updatedAt(): ?\DateTimeImmutable134    {135        return $this->updatedAt;136    }137}

Exceptions carry the name of the rule that was broken. ProjectOwnerCannotBeRemovedException extends \DomainException and offers a static factory method; the shape is shown in the chapter Implementation in Symfony 8.

The version column with #[ORM\Version] turns on optimistic locking. The example handlers, however, do not pass the version anywhere, so a conflict is detected only by Doctrine during flush(). Checking the expected version in the handler (find($id, LockMode::OPTIMISTIC, $expectedVersion)) is a step the study leaves out.

rename() and changeDescription() emit no event. The projection from section 24.06 never learns about the change, and the read model stays stale until the reconciler runs. A difference in the name is exactly the kind of discrepancy the reconciler evens out.

Domain model: Task (aggregate root)

php src/TaskManagement/Domain/Model/Task.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\Domain\Model;6 7use App\TaskManagement\Domain\Event\TaskCreated;8use App\TaskManagement\Domain\Event\TaskAssigned;9use App\TaskManagement\Domain\Event\TaskStatusChanged;10use App\TaskManagement\Domain\Exception\InvalidTaskStateTransitionException;11use App\TaskManagement\Domain\ValueObject\TaskId;12use App\TaskManagement\Domain\ValueObject\TaskStatus;13use App\SharedKernel\Domain\AggregateRoot;14// ProjectId and UserId are imported from their owning contexts (see section 24.07.2)15use App\ProjectManagement\Domain\ValueObject\ProjectId;16use App\UserManagement\Domain\ValueObject\UserId;17use Doctrine\ORM\Mapping as ORM;18 19#[ORM\Entity]20#[ORM\Table(name: 'tasks')]21final class Task extends AggregateRoot22{23    #[ORM\Id]24    #[ORM\Column(type: 'task_id')]25    private TaskId $id; // no readonly: otherwise getReference() ends with a LogicException26 27    #[ORM\Column(type: 'string', length: 255)]28    private string $title;29 30    #[ORM\Column(type: 'text', nullable: true)]31    private ?string $description;32 33    #[ORM\Column(type: 'project_id')]34    private readonly ProjectId $projectId;35 36    #[ORM\Column(type: 'user_id', nullable: true)]37    private ?UserId $assigneeId = null;38 39    #[ORM\Column(type: 'string', length: 20, enumType: TaskStatus::class)]40    private TaskStatus $status;41 42    #[ORM\Column(type: 'datetime_immutable')]43    private readonly \DateTimeImmutable $createdAt;44 45    #[ORM\Column(type: 'datetime_immutable', nullable: true)]46    private ?\DateTimeImmutable $updatedAt = null;47 48    private function __construct(TaskId $id, string $title, ?string $description, ProjectId $projectId)49    {50        $this->id = $id;51        $this->title = $title;52        $this->description = $description;53        $this->projectId = $projectId;54        $this->status = TaskStatus::Todo;55        $this->createdAt = new \DateTimeImmutable();56    }57 58    public static function create(TaskId $id, string $title, ?string $description, ProjectId $projectId): self59    {60        $task = new self($id, $title, $description, $projectId);61        $task->record(new TaskCreated($id, $title, $projectId));62 63        return $task;64    }65 66    public function id(): TaskId67    {68        return $this->id;69    }70 71    public function title(): string72    {73        return $this->title;74    }75 76    public function description(): ?string77    {78        return $this->description;79    }80 81    public function projectId(): ProjectId82    {83        return $this->projectId;84    }85 86    public function assigneeId(): ?UserId87    {88        return $this->assigneeId;89    }90 91    public function status(): TaskStatus92    {93        return $this->status;94    }95 96    public function assign(UserId $assigneeId): void97    {98        $this->assigneeId = $assigneeId;99        $this->updatedAt = new \DateTimeImmutable();100 101        $this->record(new TaskAssigned($this->id, $assigneeId));102    }103 104    public function unassign(): void105    {106        $this->assigneeId = null;107        $this->updatedAt = new \DateTimeImmutable();108    }109 110    public function changeStatus(TaskStatus $status): void111    {112        if (!$this->status->canTransitionTo($status)) {113            throw InvalidTaskStateTransitionException::cannotTransition(114                $this->status->value,115                $status->value,116            );117        }118 119        $oldStatus = $this->status;120        $this->status = $status;121        $this->updatedAt = new \DateTimeImmutable();122 123        $this->record(new TaskStatusChanged($this->id, $oldStatus, $status));124    }125 126    public function updateTitle(string $title): void127    {128        $this->title = $title;129        $this->updatedAt = new \DateTimeImmutable();130    }131 132    public function updateDescription(?string $description): void133    {134        $this->description = $description;135        $this->updatedAt = new \DateTimeImmutable();136    }137 138    public function createdAt(): \DateTimeImmutable139    {140        return $this->createdAt;141    }142 143    public function updatedAt(): ?\DateTimeImmutable144    {145        return $this->updatedAt;146    }147}

Domain events

Aggregates record facts that matter to the domain. An event is an immutable record of something that happened in the past, so all the classes are final readonly with public promoted parameters. The occurredAt property carries the moment the event occurred. The default new \DateTimeImmutable(), however, takes over the server's time zone; only an explicitly passed value guarantees UTC. The payload contains the minimal set of identifiers and values needed to reconstruct the context. The theoretical basis of domain events is in the chapter DDD Building Blocks; the connection to Event Sourcing is in the chapter Event Sourcing.

php src/ProjectManagement/Domain/Event/ProjectCreated.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Domain\Event;6 7use App\ProjectManagement\Domain\ValueObject\ProjectId;8use App\UserManagement\Domain\ValueObject\UserId;9 10final readonly class ProjectCreated11{12    public function __construct(13        public ProjectId $projectId,14        public string $name,15        // The description belongs in the payload even though no invariant guards it.16        // The read model has a column for it, and what the event does not carry, the projection17        // has nowhere to get – and nobody notices, because nothing fails.18        public ?string $description,19        public UserId $ownerId,20        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),21    ) {22    }23}
php src/ProjectManagement/Domain/Event/MemberAdded.php + MemberRemoved.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Domain\Event;6 7use App\ProjectManagement\Domain\ValueObject\ProjectId;8use App\UserManagement\Domain\ValueObject\UserId;9 10final readonly class MemberAdded11{12    public function __construct(13        public ProjectId $projectId,14        public UserId $userId,15        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),16    ) {17    }18}19 20final readonly class MemberRemoved21{22    public function __construct(23        public ProjectId $projectId,24        public UserId $userId,25        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),26    ) {27    }28}
php src/TaskManagement/Domain/Event/TaskCreated.php + TaskAssigned.php + TaskStatusChanged.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\Domain\Event;6 7use App\ProjectManagement\Domain\ValueObject\ProjectId;8use App\TaskManagement\Domain\ValueObject\TaskId;9use App\TaskManagement\Domain\ValueObject\TaskStatus;10use App\UserManagement\Domain\ValueObject\UserId;11 12final readonly class TaskCreated13{14    public function __construct(15        public TaskId $taskId,16        public string $title,17        public ProjectId $projectId,18        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),19    ) {20    }21}22 23final readonly class TaskAssigned24{25    public function __construct(26        public TaskId $taskId,27        public UserId $assigneeId,28        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),29    ) {30    }31}32 33final readonly class TaskStatusChanged34{35    public function __construct(36        public TaskId $taskId,37        public TaskStatus $oldStatus,38        public TaskStatus $newStatus,39        public \DateTimeImmutable $occurredAt = new \DateTimeImmutable(),40    ) {41    }42}

Value objects: identifiers and task status

The identifiers ProjectId, TaskId, and UserId share the same structure: the constructor only validates the string it receives, and the static method generate() issues a new UUID. The $value property carries the raw string for persistence, and equals() compares by value. TaskStatus is an enum whose cases name the states in the domain language. A full discussion of value objects is in the chapter DDD Building Blocks.

php src/ProjectManagement/Domain/ValueObject/ProjectId.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Domain\ValueObject;6 7use Symfony\Component\Uid\Uuid;8 9final readonly class ProjectId10{11    public function __construct(12        public string $value,13    ) {14        if (!Uuid::isValid($value)) {15            throw new \InvalidArgumentException(16                sprintf('Invalid ProjectId: "%s".', $value),17            );18        }19    }20 21    public static function generate(): self22    {23        return new self((string) Uuid::v7());24    }25 26    public static function fromString(string $value): self27    {28        return new self($value);29    }30 31    public function equals(self $other): bool32    {33        return $this->value === $other->value;34    }35 36    // Doctrine builds the identity map key with implode() over the identifier.37    // Without __toString(), persist() already fails.38    public function __toString(): string39    {40        return $this->value;41    }42}
php src/TaskManagement/Domain/ValueObject/TaskStatus.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\Domain\ValueObject;6 7enum TaskStatus: string8{9    case Todo       = 'todo';10    case InProgress = 'in_progress';11    case Done       = 'done';12 13    public function canTransitionTo(self $next): bool14    {15        return match ([$this, $next]) {16            [self::Todo,       self::InProgress] => true,17            [self::InProgress, self::Done]       => true,18            [self::InProgress, self::Todo]       => true,19            default                              => false,20        };21    }22}

The transition table uses match over an array of two cases. The comparison is strict and, for arrays, runs element by element; enum cases are singletons, so the pair [$this, $next] hits exactly one row of the table. The notation is compact, at the price that the reader has to read it twice.

Command: creating a project (Command Pattern)

php src/ProjectManagement/CreateProject/Command/CreateProject.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\CreateProject\Command;6 7use Symfony\Component\Validator\Constraints as Assert;8 9class CreateProject10{11    public function __construct(12        #[Assert\NotBlank]13        #[Assert\Length(min: 3, max: 255)]14        public readonly string $name,15 16        public readonly ?string $description,17 18        #[Assert\NotBlank]19        #[Assert\Uuid]20        public readonly string $ownerId21    ) {22    }23}

Command handler: handling project creation (Application Service)

php src/ProjectManagement/CreateProject/Command/CreateProjectHandler.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\CreateProject\Command;6 7use App\ProjectManagement\Domain\Model\Project;8use App\ProjectManagement\Domain\Repository\ProjectRepository;9use App\ProjectManagement\Domain\ValueObject\ProjectId;10use App\UserManagement\Domain\ValueObject\UserId;11use Doctrine\ORM\EntityManagerInterface;12use Symfony\Component\Messenger\Attribute\AsMessageHandler;13use Symfony\Component\Messenger\MessageBusInterface;14 15#[AsMessageHandler(bus: 'command.bus')]16final class CreateProjectHandler17{18    public function __construct(19        private readonly ProjectRepository $projectRepository,20        private readonly EntityManagerInterface $em,21        private readonly MessageBusInterface $eventBus,22    ) {23    }24 25    public function __invoke(CreateProject $command): string26    {27        $project = Project::create(28            ProjectId::generate(),29            $command->name,30            $command->description,31            new UserId($command->ownerId),32        );33 34        $this->projectRepository->save($project); // persist the aggregate35        $this->em->flush();                       // write SQL; the command bus middleware controls the commit36 37        foreach ($project->releaseEvents() as $event) {38            $this->eventBus->dispatch($event);39        }40 41        return $project->id->value;42    }43}

The order save() → flush() → releaseEvents() → dispatch() is deliberate. Publishing before the flush means announcing a change the database may still reject. The commit, however, is controlled by the doctrine_transaction middleware only after the handler returns, so the dispatch runs inside an open transaction. A synchronous listener does not mind; a rollback reverts its writes too. A message on an asynchronous transport, however, leaves before the commit succeeds. This gap and the way around it through a transactional table are discussed in DDD Building Blocks and in the chapter Outbox Pattern.

The handler generates the ProjectId itself and returns it to the caller. A return value from a command handler keeps the command on a synchronous bus. Once the command moved to an asynchronous transport, the ID would have to originate with the caller and travel inside the command (CQRS).

Command: assigning a task (Command Pattern)

php src/TaskManagement/AssignTask/Command/AssignTask.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\AssignTask\Command;6 7use Symfony\Component\Validator\Constraints as Assert;8 9class AssignTask10{11    public function __construct(12        #[Assert\NotBlank]13        #[Assert\Uuid]14        public readonly string $taskId,15 16        #[Assert\NotBlank]17        #[Assert\Uuid]18        public readonly string $assigneeId19    ) {20    }21}

Command handler: handling task assignment (Application Service)

The ProjectChecker port is an interface in the TaskManagement domain. The implementation lives in the infrastructure and translates the query into a call to the upstream context:

php src/TaskManagement/Domain/Port/ProjectChecker.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\Domain\Port;6 7use App\ProjectManagement\Domain\ValueObject\ProjectId;8use App\UserManagement\Domain\ValueObject\UserId;9 10interface ProjectChecker11{12    public function exists(ProjectId $projectId): bool;13 14    public function isMember(ProjectId $projectId, UserId $userId): bool;15}
php src/TaskManagement/AssignTask/Command/AssignTaskHandler.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\AssignTask\Command;6 7use App\TaskManagement\Domain\Exception\AssigneeNotProjectMemberException;8use App\TaskManagement\Domain\Exception\ProjectNotFoundException;9use App\TaskManagement\Domain\Port\ProjectChecker;10use App\TaskManagement\Domain\Repository\TaskRepository;11use App\TaskManagement\Domain\Service\TaskAssignmentService;12use App\TaskManagement\Domain\ValueObject\TaskId;13use App\UserManagement\Domain\ValueObject\UserId;14use Doctrine\ORM\EntityManagerInterface;15use Symfony\Component\Messenger\Attribute\AsMessageHandler;16use Symfony\Component\Messenger\MessageBusInterface;17 18#[AsMessageHandler(bus: 'command.bus')]19final class AssignTaskHandler20{21    public function __construct(22        private readonly TaskRepository $taskRepository,23        private readonly ProjectChecker $projectChecker,24        private readonly TaskAssignmentService $taskAssignmentService,25        private readonly EntityManagerInterface $em,26        private readonly MessageBusInterface $eventBus,27    ) {28    }29 30    public function __invoke(AssignTask $command): void31    {32        $taskId = new TaskId($command->taskId);33        // get() does not return a missing task as null; it throws TaskNotFoundException.34        $task = $this->taskRepository->get($taskId);35 36        $assigneeId = new UserId($command->assigneeId);37 38        // Verification through the port – without a direct dependency on ProjectManagement39        if (!$this->projectChecker->exists($task->projectId())) {40            throw ProjectNotFoundException::withId($task->projectId()->value);41        }42 43        if (!$this->projectChecker->isMember($task->projectId(), $assigneeId)) {44            throw AssigneeNotProjectMemberException::forTask($taskId->value, $assigneeId->value);45        }46 47        // The domain service holds the assignment rule48        $this->taskAssignmentService->assignTask($task, $assigneeId);49 50        $this->taskRepository->save($task);51        $this->em->flush();52 53        foreach ($task->releaseEvents() as $event) {54            $this->eventBus->dispatch($event);55        }56    }57}

The handler verifies a domain rule: the assignee must be a member of the project. The question of who may assign the task is not addressed here. Permissions belong to an authorization layer above the handler, which is covered in the chapter Authorization in DDD.

Query: getting a user's projects (Query Pattern)

php src/ProjectManagement/GetProjects/Query/GetProjects.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\GetProjects\Query;6 7use Symfony\Component\Validator\Constraints as Assert;8 9class GetProjects10{11    public function __construct(12        #[Assert\NotBlank]13        #[Assert\Uuid]14        public readonly string $userId15    ) {16    }17}

Query handler: handling the user's projects query (read model)

php src/ProjectManagement/GetProjects/Query/GetProjectsHandler.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\GetProjects\Query;6 7use App\ProjectManagement\Domain\Repository\ProjectRepository;8use App\ProjectManagement\GetProjects\ViewModel\ProjectViewModel;9use App\UserManagement\Domain\ValueObject\UserId;10use Symfony\Component\Messenger\Attribute\AsMessageHandler;11 12#[AsMessageHandler(bus: 'query.bus')]13class GetProjectsHandler14{15    public function __construct(16        private readonly ProjectRepository $projectRepository17    ) {18    }19 20    public function __invoke(GetProjects $query): array21    {22        $projects = $this->projectRepository->findByMemberId(new UserId($query->userId));23 24        $result = [];25 26        foreach ($projects as $project) {27            $result[] = new ProjectViewModel(28                $project->id->value,29                $project->name(),30                $project->description(),31                $project->ownerId->value,32                count($project->memberIds()),33                0, // the naive version does not know the task count – Task is a separate aggregate (see section 24.06)34                $project->createdAt35            );36        }37 38        return $result;39    }40}

Domain service: task assignment

php src/TaskManagement/Domain/Service/TaskAssignmentService.php
1<?php2 3declare(strict_types=1);4 5namespace App\TaskManagement\Domain\Service;6 7use App\TaskManagement\Domain\Model\Task;8use App\UserManagement\Domain\ValueObject\UserId;9 10class TaskAssignmentService11{12    // The domain service works exclusively with objects of its own Bounded Context.13    // The handler verifies project membership through the ProjectChecker port.14    public function assignTask(Task $task, UserId $assigneeId): void15    {16        $task->assign($assigneeId);17    }18}

24.06 Read models and projections#

GetProjectsHandler from the previous section loads projects through the domain repository. It hydrates aggregates even though it needs only a tabular listing. With small data, that works. Once the data grows to thousands of projects and tens of thousands of tasks, and the listing is enriched with member names and task counts, every query means repeated JOINs and hydrating aggregates for display.

So the project gradually gained a separate read model. The principle: domain events update a denormalized table that the query handler reads from. No JOIN between aggregates, no hydration of domain objects. The deeper theoretical basis is in the chapters CQRS and Read Models, Projections, and Performance.

Read model schema

The project_list_view table holds the shape needed for listing a user's projects. It is not normalized: it contains computed values (member_count, task_count) and the denormalized field member_ids as JSON. It is not the source of truth; it can be rebuilt from the primary tables at any time. Both the @> query and the GIN index assume a PostgreSQL column of type jsonb. Types::JSON creates a json column, on which neither @> nor a GIN index works; since DBAL 4.3 there is a Types::JSONB type for this. Older versions (DBAL 3.x to 4.2) only have the option ['jsonb' => true], which the same version 4.3 deprecated.

The read model entity does not carry readOnly: true. The flag turns off change tracking, so only persist() would get through from the projection, and every UPDATE would silently vanish; yet updates are exactly what a projection does most often.

php src/ProjectManagement/Infrastructure/ReadModel/ProjectListView.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Infrastructure\ReadModel;6 7use Doctrine\DBAL\Types\Types;8use Doctrine\ORM\Mapping as ORM;9 10#[ORM\Entity]11#[ORM\Table(name: 'project_list_view')]12#[ORM\Index(columns: ['owner_id'], name: 'idx_owner')]13class ProjectListView14{15    #[ORM\Id]16    #[ORM\Column(type: Types::GUID)]17    public string $projectId;18 19    #[ORM\Column(type: Types::STRING, length: 255)]20    public string $name;21 22    #[ORM\Column(type: Types::TEXT, nullable: true)]23    public ?string $description = null;24 25    #[ORM\Column(type: Types::GUID)]26    public string $ownerId;27 28    // PostgreSQL: jsonb, not json – neither the @> operator nor a GIN index works on json.29    // Types::JSONB requires DBAL 4.3+; older versions: Types::JSON with options ['jsonb' => true].30    #[ORM\Column(type: Types::JSONB)]31    public array $memberIds = [];32 33    #[ORM\Column(type: Types::INTEGER)]34    public int $memberCount = 0;35 36    #[ORM\Column(type: Types::INTEGER)]37    public int $taskCount = 0;38 39    #[ORM\Column(type: Types::DATETIME_IMMUTABLE)]40    public \DateTimeImmutable $createdAt;41 42    #[ORM\Column(type: Types::DATETIME_IMMUTABLE)]43    public \DateTimeImmutable $updatedAt;44}

You will not find the GIN index on member_ids in the mapping. The #[ORM\Index] attribute does know a flags parameter, but PostgreSQLPlatform does not translate it, and it never reaches the DDL; the result would be an ordinary B-tree index, which a query with @> would not use anyway. The index is therefore created by a manual migration:

sql migrations/Version20250424120000.php (excerpt)
1CREATE INDEX idx_members ON project_list_view USING gin (member_ids);

Projection: updating the read model from events

The projection listens to domain events from all contexts that affect the shape of the project listing. It runs as an asynchronous message handler outside the original transaction, so it cannot bring that transaction down. Each event is handled by a separate method with the #[AsMessageHandler(bus: 'event.bus')] attribute; Messenger routes by the parameter's type hint, so a generic object type hint cannot be used.

The projection handles four of the six events the aggregates emit. The chapter does not list the ActivityTracking handler, so TaskAssigned and TaskStatusChanged have no consumer in the examples. On an asynchronous transport they would therefore end up in retry and then in the dead-letter queue. For that reason, the event bus needs allow_no_handlers: true, as described in the CQRS chapter.

php src/ProjectManagement/Infrastructure/ReadModel/ProjectListProjection.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Infrastructure\ReadModel;6 7use App\ProjectManagement\Domain\Event\MemberAdded;8use App\ProjectManagement\Domain\Event\MemberRemoved;9use App\ProjectManagement\Domain\Event\ProjectCreated;10use App\TaskManagement\Domain\Event\TaskCreated;11use Doctrine\DBAL\Exception\UniqueConstraintViolationException;12use Doctrine\ORM\EntityManagerInterface;13use Doctrine\Persistence\ManagerRegistry;14use Symfony\Component\Messenger\Attribute\AsMessageHandler;15 16class ProjectListProjection17{18    public function __construct(19        private readonly EntityManagerInterface $em,20        private readonly ManagerRegistry $registry,21    ) {22    }23 24    #[AsMessageHandler(bus: 'event.bus')]25    public function onProjectCreated(ProjectCreated $event): void26    {27        if ($this->em->find(ProjectListView::class, $event->projectId->value) !== null) {28            return; // the event has already been processed29        }30 31        $now = new \DateTimeImmutable();32        $view = new ProjectListView();33        $view->projectId = $event->projectId->value;34        $view->name = $event->name;35        $view->description = $event->description;36        $view->ownerId = $event->ownerId->value;37        $view->memberIds = [$event->ownerId->value];38        $view->memberCount = 1;39        $view->taskCount = 0;40        $view->createdAt = $now;41        $view->updatedAt = $now;42        $this->em->persist($view);43 44        try {45            $this->em->flush();46        } catch (UniqueConstraintViolationException) {47            // Concurrency: another worker managed to insert the row between find() and flush().48            // The result is the same one we wanted, so we acknowledge the message.49            //50            // The failed flush, however, closed the EntityManager, and clear() does not reopen it.51            // Without a reset, the next handler in the same process would end with52            // EntityManagerClosed. More detail in the chapter53            // [DDD in Practice – Where It Hurts](/ddd-v-praxi-kde-to-boli#a1-transakce).54            $this->registry->resetManager();55        }56    }57 58    #[AsMessageHandler(bus: 'event.bus')]59    public function onMemberAdded(MemberAdded $event): void60    {61        $view = $this->em->find(ProjectListView::class, $event->projectId->value);62        if ($view === null) {63            // Out-of-order delivery: MemberAdded arrived before ProjectCreated.64            // The reconciler (see Projection idempotence and reconciliation) finds the missing row and restores it65            // from the source aggregates.66            return;67        }68        $userId = $event->userId->value;69        if (!in_array($userId, $view->memberIds, strict: true)) {70            $view->memberIds[] = $userId;71            $view->memberCount++;72            $view->updatedAt = new \DateTimeImmutable();73            $this->em->flush();74        }75    }76 77    #[AsMessageHandler(bus: 'event.bus')]78    public function onMemberRemoved(MemberRemoved $event): void79    {80        $view = $this->em->find(ProjectListView::class, $event->projectId->value);81        if ($view === null) {82            return;83        }84        $userId = $event->userId->value;85        $view->memberIds = array_values(array_filter(86            $view->memberIds,87            static fn(string $id): bool => $id !== $userId88        ));89        $view->memberCount = count($view->memberIds);90        $view->updatedAt = new \DateTimeImmutable();91        $this->em->flush();92    }93 94    #[AsMessageHandler(bus: 'event.bus')]95    public function onTaskCreated(TaskCreated $event): void96    {97        $view = $this->em->find(ProjectListView::class, $event->projectId->value);98        if ($view === null) {99            return;100        }101        $view->taskCount++;102        $view->updatedAt = new \DateTimeImmutable();103        $this->em->flush();104    }105}

Query handler over the read model (revised GetProjectsHandler)

The naive version from section 24.05 hydrated domain aggregates only for display. After the projection was introduced, the GetProjectsHandler class was rewritten as a plain DBAL query over the read table: no aggregates and no domain logic, only selecting columns and mapping them to ProjectViewModel. The class name and the GetProjects query stayed the same; only the implementation changed. Neither the callers nor Symfony Messenger know about the change.

php src/ProjectManagement/GetProjects/Query/GetProjectsHandler.php (over the read model)
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\GetProjects\Query;6 7use App\ProjectManagement\GetProjects\ViewModel\ProjectViewModel;8use Doctrine\DBAL\Connection;9use Symfony\Component\Messenger\Attribute\AsMessageHandler;10 11#[AsMessageHandler(bus: 'query.bus')]12class GetProjectsHandler13{14    public function __construct(15        private readonly Connection $db16    ) {17    }18 19    /** @return ProjectViewModel[] */20    public function __invoke(GetProjects $query): array21    {22        $rows = $this->db->fetchAllAssociative(23            'SELECT project_id, name, description, owner_id, member_count, task_count, created_at24             FROM project_list_view25             WHERE member_ids @> :userId26             ORDER BY updated_at DESC',27            ['userId' => json_encode([$query->userId])]28        );29 30        return array_map(31            static fn(array $row): ProjectViewModel => new ProjectViewModel(32                projectId:   $row['project_id'],33                name:        $row['name'],34                description: $row['description'],35                ownerId:     $row['owner_id'],36                memberCount: (int) $row['member_count'],37                taskCount:   (int) $row['task_count'],38                createdAt:   new \DateTimeImmutable($row['created_at']),39            ),40            $rows41        );42    }43}

Projection idempotence and reconciliation

Asynchronous delivery through Messenger does not guarantee message order. When the transport splits messages among several workers, MemberAdded can arrive before ProjectCreated for the same project. The projection therefore needs two properties.

Idempotence. Processing the same event again must not change the result. In the example above, three details take care of that. onProjectCreated first looks for an existing row and, on a second delivery, ends without writing; find() alone is not enough, though, because another worker can insert the row between it and flush(), which is why the code also catches the primary key violation. onMemberAdded does not add a user twice thanks to the in_array(..., strict: true) check. onMemberRemoved recalculates memberCount from the current length of the array instead of incrementing it.

A weak spot remains in onTaskCreated. Incrementing taskCount on a repeated delivery adds an extra one. Pushing the problem off to Messenger's retry strategy (three retries by default) and from there to the failure transport is not idempotence, only a failure swept aside. The solution goes through the event's identity: each event will carry its own eventId, and the projection will remember the processed IDs. The current classes carry only occurredAt, so this is a change to the payload. DeduplicateMiddleware with the DeduplicateStamp stamp (Messenger since version 7.3) does not replace this change. Its lock holds only from dispatch until handling, so it stops a duplicate dispatch of a pending message but lets a repeated delivery through. The full idempotent-receiver pattern is described in the chapter Outbox Pattern.

Reconciler. When an event arrives out of order (the handler ends without writing because $view === null) or gets lost, the projection stays stale. The reconciler is a separate process that looks for differences between the write and the read model at a regular interval and fills in the missing data. In the study, it is a Symfony console command run from cron once an hour (the frequency is a compromise between freshness and database load):

php src/ProjectManagement/Infrastructure/ReadModel/ReconcileProjectListView.php
1<?php2 3declare(strict_types=1);4 5namespace App\ProjectManagement\Infrastructure\ReadModel;6 7use App\ProjectManagement\Domain\Repository\ProjectRepository;8use Doctrine\ORM\EntityManagerInterface;9use Symfony\Component\Console\Attribute\AsCommand;10use Symfony\Component\Console\Command\Command;11use Symfony\Component\Console\Style\SymfonyStyle;12 13#[AsCommand(14    name: 'project-list:reconcile',15    description: 'Brings the stale project_list_view read model up to date from the source aggregates.',16)]17final class ReconcileProjectListView18{19    public function __construct(20        private readonly ProjectRepository $projects,21        private readonly EntityManagerInterface $em,22    ) {23    }24 25    public function __invoke(SymfonyStyle $io): int26    {27        $now = new \DateTimeImmutable();28        $repaired = 0;29 30        foreach ($this->projects->all() as $project) {31            $view = $this->em->find(ProjectListView::class, $project->id->value);32            $expectedMembers = array_map(33                static fn($id) => $id->value,34                $project->memberIds(),35            );36 37            if ($view === null) {38                // Missing view: create it and fill in all fields right away.39                $view = new ProjectListView();40                $view->projectId   = $project->id->value;41                $view->ownerId     = $project->ownerId->value;42                $view->createdAt   = $project->createdAt;43                $view->name        = $project->name();44                $view->description = $project->description();45                $view->memberIds   = $expectedMembers;46                $view->memberCount = count($expectedMembers);47                $view->updatedAt   = $now;48                $this->em->persist($view);49                $repaired++;50                continue;51            }52 53            // Membership is a set: a different order after out-of-order delivery needs no repair.54            $viewMembers = $view->memberIds;55            $sortedExpected = $expectedMembers;56            sort($viewMembers);57            sort($sortedExpected);58 59            $needsRepair = $view->name !== $project->name()60                || $view->description !== $project->description()61                || $viewMembers !== $sortedExpected62                || $view->memberCount !== count($expectedMembers);63 64            if (!$needsRepair) {65                continue;66            }67 68            $view->name        = $project->name();69            $view->description = $project->description();70            $view->memberIds   = $expectedMembers;71            $view->memberCount = count($expectedMembers);72            $view->updatedAt   = $now;73            $repaired++;74        }75 76        $this->em->flush();77        $io->writeln(sprintf('Reconciled %d projects.', $repaired));78 79        return Command::SUCCESS;80    }81}

The command uses the invokable syntax that Symfony has recommended since version 7.3. Extending the Command class remains supported; it is only listed as the older form.

The reconciler does not replace the projection; it only evens out what the projection failed to deliver for technical reasons. In production, an alert on the number of reconciled records pays off: a high number signals a systemic problem with the transport, not a minor reshuffling of message order.

What this version does not reconcile: task_count (it could be computed from TaskRepository), ownerId and createdAt on an already existing row, and orphaned rows left after deleted projects. Nor does it handle volume: $this->projects->all() hydrates all aggregates at once. With thousands of projects, the loop needs batching by a few hundred items, EntityManager::clear() after each batch, and --limit and --dry-run switches.

Consistency implications

The read model is eventually consistent. Between the commit of a write and the projection update, there is a window (typically milliseconds, seconds when Messenger is under load) in which the returned list does not contain a newly created project. The team covered it in two ways:

  • Optimistic UI update – after a successful response to a command, the client adds the record to its local state and loads the updated read model only on the next navigation. The user sees the result of their action immediately.
  • Read-your-writes through the write model – for critical queries right after a command (e.g., the Detail of a newly created project page), the handler reads directly from the write model or from a cache keyed by the ID of the operation that just completed. The cost: losing the read model's benefits for this one flow.

24.07 Challenges and decisions#

The five decisions below show the places where the team hesitated between two defensible options. Instead of a “correct” answer, there is a context that determined the choice and a price the team pays for it. In another project, the same question could turn out differently. The final subsection sums up what the team would do differently today.

1. Eventual consistency across contexts

Question: should writing an activity in ActivityTracking be part of the same transaction as the originating operation (e.g., writing a project), or an asynchronous reaction to a published event?

Choice: asynchronous processing through a Messenger transport. The audit must not become a critical point of failure for the main use case. That property, however, is only guaranteed by an outbox table, which the examples in this chapter do not have (Outbox Pattern). With it, the project write completes even when the transport is unavailable, and the activity is recorded as soon as the transport is back up. Without it, the dispatch inside the transaction fails, and the middleware rolls back the project write too.

Cost: a user with the auditor role sees a new activity with a delay. For an audit log, where the reader is not the author of the action, the delay is acceptable. For real-time notifications, the compromise would not be enough; there, synchronous integration or a websocket push from the projection helps.

2. Shared identifiers as a Shared Kernel

Question: UserId appears in all contexts (project owner, assignee, comment author). Will there be one shared class that the other contexts import, or will each context keep its own representation as a primitive string?

Choice: one class in the owning context, imported by the others. UserId lives in UserManagement, ProjectId in ProjectManagement, TaskId in TaskManagement; downstream contexts use these value objects directly. The pattern has a name: Shared Kernel, a small jointly owned part of the model that none of the contexts can change on its own. There is only one team and one deployment, and the risk that the UUID format diverges between contexts is negligible. The shared class also keeps validation in one place.

Cost: a dependency on another context's domain layer. When the owning context extends UserId with new validation, it affects all the others. Refactoring a class shared this way is, in practice, a coordinated release.

Alternative: If the team split or the contexts were separated into standalone services, a primitive string would be safer (each context validates on its own) at the cost of duplication. For a monolith with a single deployment pipeline, the shared class is more pragmatic.

3. Synchronous check through a port vs. asynchronous reaction to an event

Question: when assigning a task (AssignTask), TaskManagement has to verify that the user being assigned is a member of the project. A synchronous call to the ProjectChecker port, or a purely asynchronous reaction to TaskAssignmentRequested with compensation if the membership does not hold?

Choice: a synchronous port. The operation must fail immediately if the user is not a member of the project. The user waits for the command's response and wants to know right away whether the assignment went through, or why not.

Cost: TaskManagement has a temporal dependency on ProjectManagement. If the other context is unavailable, the assignment fails. In a monolith, this dependency is invisible; in a world of services, it adds a network hop and the risk of cascading failures.

Alternative for a distributed system: TaskManagement would keep a local “project members” projection updated by events from ProjectManagement. Validation would run against a local table, without a network call. For a monolith, this is premature optimization, but once the contexts were separated, it is the first refactoring that should take place. When such a separation pays off and what it costs is discussed in the chapter DDD and Microservices. If validation failed only after the assignment was completed, a compensation scenario would revert the state, a pattern described in the chapter Sagas and Process Managers.

4. Domain service vs. logic in the handler

Question: TaskAssignmentService::assignTask() currently only calls Task::assign(). Does a domain service that only delegates make sense?

Choice: keep it as a place for extension. Task assignment is a domain concept that will likely grow in the future: notifying the assignee, checking workload, validating deadlines, integrating with a calendar. The existing abstraction allows these rules to be added without changing the handler, the controller, or the aggregate itself.

Cost: a currently empty abstraction that may seem superfluous to a reader of the code. The chapter Implementation in Symfony 8 labels a domain service that merely wraps a call to a single aggregate as an anti-pattern: it weakens the aggregate and leads to an anemic model. The exception made here stands or falls on whether rules around assignment really get added. If they do not, the anti-pattern applies, and the service should go.

Alternative: an inline call in the handler and a refactoring at the moment the first reason for a domain service appears, that is, YAGNI in practice. Both paths are defensible in DDD, and the choice between them is a matter of team agreement.

5. Size of the Project aggregate

Question: should Project contain a list of tasks (Task[]) and be a large aggregate, or are Project and Task two separate aggregates connected through ProjectId?

Choice: two separate aggregates. Task holds ProjectId as a reference, but it is not inside Project.

Reasons:

  • Concurrent task additions by different users do not collide on one aggregate. In a large Project, they would either clash on the project's version, if the handler bumps it manually, or silently bypass the invariant over the collection. Doctrine does not bump the root's version on its own when a child changes (see Anti-Patterns and Common Mistakes).
  • A project can be loaded without its tasks, so listing projects stays cheap.
  • A task's transaction changes only the task. The size of the project has no effect on it.

Cost: the invariant “a task belongs to an existing project” is enforced at the handler level (through ProjectChecker), not in the domain model. A direct write to the database (e.g., a data import) can create a task without a project. A foreign key on project_id prevents that at the database level.

Alternative: If the application required the invariant “a project must not have more than 50 tasks,” there are two paths. Move the rule into a domain service with an explicit contract, or make Task a component inside the Project aggregate – less scalable, but consistent with that invariant. The rules for aggregate size and its transactional boundary are covered in Aggregate Design, and anti-patterns such as the God Aggregate in Anti-Patterns and Common Mistakes.

What would be done differently today

The team would do three things differently today.

rename() and changeDescription() do not emit an event. The read model never learns about the name change and stays stale until the reconciler runs. The fix is a ProjectRenamed event, not an hourly cron job.

The events published to ActivityTracking carry internal value objects of the publishing context. As long as the monolith runs, nobody feels it. The first consumer outside the repository, however, will freeze the domain model in whatever shape it happens to be in.

TaskAssignmentService is still empty. The extension it was created for never arrived, so according to decision 4, the anti-pattern applies and the service should go.

A catalog of similar friction points is in the chapter DDD in Practice – Where It Hurts: from Doctrine through message ordering to Ubiquitous Language drift.

24.08 Lessons learned#

The design described above yields ten points that hold outside this study as well.

  1. Strategic design decides the outcome – Identifying the five Bounded Contexts and their relationships at the start of the project revealed that the word “user” means something different in each context. Without a Context Map, this semantic difference would have surfaced only in arguments over pull requests.
  2. Ubiquitous Language sharpens the model – A common language with the domain experts removed ambiguities in the requirements and was mirrored directly in the names of classes and methods. The tester, the developer, and the product manager all talk about TaskAssigned instead of each meaning something else.
  3. Aggregates and transaction boundaries – Small, clearly delimited aggregates kept the data consistent: each guarded its own invariants and changed in a single transaction.
  4. Domain events for integration – Where a reaction can tolerate a delay, domain events decoupled the Bounded Contexts from synchronous calls. After a task was created, the aggregate published a TaskCreated event; ActivityTracking and ProjectListProjection reacted to it independently, without knowing about each other. Verifying membership when assigning a task stayed synchronous, because it has to fail right away (decision 3).
  5. CQRS for separating responsibilities – Commands change state; queries read without side effects. Each side has its own handler, its own model, and its own tests. Symfony Messenger took on the role of the message bus.
  6. Vertical slice architecture for modularity – Organizing code by features instead of technical layers meant that a change in one feature usually does not touch the others. Each feature carries its own command, handler, controller, and view model. A new feature usually comes into being by adding a directory, not by modifying existing classes.
  7. Testing the domain model – Domain objects without framework dependencies can be tested with plain PHPUnit without booting the kernel. Unit tests verified the behavior of aggregates and domain services, integration tests the cooperation between parts of the system. A detailed strategy for DDD projects is in the chapter Testing DDD.
  8. Read models as a separate artifact – Separating the write and read sides through projections proved its value once the dataset passed several thousand projects. Hydrating aggregates for a listing is expensive; the denormalized read model removed it from the listing entirely, and instead of several JOINs and hundreds of objects, one query over one table remained. The price was eventual consistency, which the team handled with optimistic UI updates combined with read-your-writes for critical scenarios.
  9. Domain analysis comes before code – The three steps of Event Storming (collecting events, grouping them into subdomains, defining boundaries) worked as a filter against premature technical decomposition. Without this step, the context boundaries would have copied database tables or screen flow, not the semantic blocks of the domain. Two days at the whiteboard are a fraction of what it later costs to move a badly drawn boundary.
  10. Write down the trade-offs – Not every decision has one correct answer. Shared identifier classes between contexts, eventual consistency for the audit, the synchronous check through a port – each of these choices has a price the team accepted knowing the alternative. Recording these decisions in documentation (ADRs) preserved the context for later refactoring; without it, the discussion would repeat itself half a year later.

24.09 Further reading#

  • Eric Evans, Domain-Driven Design (Addison-Wesley, 2003) – a single running shipping domain that accompanies the whole book; open-source implementation citerus/dddsample-core.
  • Vaughn Vernon, Implementing Domain-Driven Design (Addison-Wesley, 2013) and the samples VaughnVernon/IDDD_Samples. The iddd_agilepm context covers practically the same domain as this study, but it keeps identity as a separate context that the others work with through translation.
  • Vlad Khononov, Learning Domain-Driven Design (O'Reilly, 2021) – a help-desk SaaS as the running example, including subdomain classification.
  • DDD Crew, DDD Starter Modelling Process – eight steps from understanding the business to code. This chapter goes through the Discover, Decompose, Strategize, Connect, Define, and Code steps; it leaves Understand and Organise aside.
  • CodelyTV/php-ddd-example – a runnable PHP reference with the structure src/<BoundedContext>/<Module>/{Application,Domain,Infrastructure} and its own aggregate base class.
  • Mathias Verraes, Patterns for Decoupling in Distributed Systems: Explicit Public Events – why only a small, deliberately marked subset of events is public.

Frequently asked questions

What domain does the case study describe?

A project and task management system: users create projects, add tasks, assign them to team members, change their status, and comment on them. The scenario is illustrative: the team, the numbers, and the decisions are fictional and serve as one continuous demonstration of the design. The domain is rich enough to cover both the strategic (Context Map) and the tactical (aggregate, domain service) patterns of DDD, yet manageable within a single chapter. The specific requirements are in the Requirements section.

Why is the system split into five Bounded Contexts instead of one model?

Each context has different semantics: UserManagement handles identity, ProjectManagement the project lifecycle, TaskManagement the state transitions of tasks, CommentManagement communication, and ActivityTracking the audit. The split reflects real domain boundaries and allows each context to evolve independently, with its own language and its own invariants. Sharing a single model would lead to an overgrown aggregate (God Aggregate) and to compromises between semantically different areas. The discussion is in the Architecture section.

How do the Bounded Contexts communicate with each other?

The primary means of integration is domain events: after an operation completes, the aggregate publishes an event (e.g., TaskCreated) that other contexts react to asynchronously through Messenger. Synchronous queries between contexts go through ports: the interface lies in the domain of the calling context, the adapter to the other context in its infrastructure. The calling context's domain thus does not depend on the details of the other one. A concrete example is in the Implementation section.

What did the vertical slice architecture bring?

Each feature (CreateProject, AssignTask, AddComment) was built as a separate package with its own command, handler, controller, and view model. A change in a feature does not reach into the other slices. Changes rippling across layers, typical of horizontal splitting, almost never occur in such a layout. A detailed comparison is in the chapter Architectural Styles.

Why does it make sense to separate the read model from the domain model?

The domain model exists to enforce invariants and represent domain rules; a project listing needs no invariants. Hydrating an aggregate only to display a name and a member count is expensive. As the dataset grows, it matters whether a listing means one query over one table or several JOINs and hundreds of assembled objects. A denormalized read model updated through projections makes it possible to separate the pace of writes and reads and to optimize each side separately. The price is eventual consistency. The concrete implementation is in the Read models and projections section.

What are the three most important lessons from the project?

First, a Context Map drawn before the code separates the meanings a single word carries in different parts of the system; without it, the difference surfaces only in arguments over pull requests. Second, a Ubiquitous Language built with domain experts keeps the same terms in the code, in the ticket, and in conversation. Third, small aggregates with a clear transactional boundary keep the model consistent without distributed transactions. The full list, including the lessons about read models and deliberate trade-offs, is in the Lessons learned section.

What was the hardest decision in the project?

The choice between synchronously verifying project membership (through the ProjectChecker port) and an asynchronous reaction through a local projection. In a monolith, the synchronous path means fewer moving parts, but it creates a temporal dependency between contexts. The study chooses the synchronous variant as a pragmatic compromise for the monolith phase, knowing that splitting into services will bring a refactoring to a local projection. The full context of the decision, including the other four trade-offs, is in the Challenges and decisions section.