Chapter 23 · Synthesis · Practical Examples

Practical Examples

Three small projects in Symfony 8: an online store, a blog, and user management. Each one shows the split into Bounded Contexts, the domain model, and vertical slice architecture.

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

Three short examples assemble the patterns from tactical DDD, CQRS, and Implementation in Symfony into a working application. Each example contains the project structure and a skeleton of the main classes; only the methods that carry a domain invariant get a full body. The details (Doctrine mapping, controllers, tests, edge cases) stay in the earlier chapters.

A full end-to-end example is worked through step by step in the following Case Study: from domain analysis through the Context Map to read models.

The starting point is an empty project: composer create-project symfony/skeleton. The samples in the book target PHP 8.4, Symfony 8, and Doctrine ORM 3 and need these packages:

bash terminal
1composer require \2    symfony/uid \3    symfony/messenger \4    symfony/doctrine-messenger \5    symfony/serializer symfony/property-access symfony/property-info \6    symfony/validator egulias/email-validator \7    symfony/security-bundle \8    symfony/twig-bundle symfony/form \9    symfony/expression-language \10    doctrine/orm doctrine/doctrine-bundle doctrine/doctrine-migrations-bundle

The list does not look minimal, but every item has a reason in one of the chapters. doctrine-messenger provides the doctrine://default transport. Without serializer and property-access the outbox fails, and without egulias/email-validator, Assert\Email with VALIDATION_MODE_STRICT brings down every dispatch. And without migrations-bundle you cannot run a single migration from the Outbox chapter. Controllers that return HTML need twig-bundle and form. The ones in the CQRS chapter call createForm() and render(). If you build only a JSON API, you can do without them. expression-language, on the other hand, is mandatory as soon as the project contains the PolicyEvaluator from the authorization chapter. It takes the component as a default parameter value, so without the package even cache:clear fails, not only the evaluation of a rule.

Installation does not end there. The next two steps tend to get skipped, because leaving them out does not show right away. The doctrine/doctrine-bundle recipe generates a mapping to src/Entity with the App\Entity prefix, that is, to a directory that does not exist in a vertical slice layout. Doctrine then silently sees no entity at all:

bash terminal
1php bin/console doctrine:schema:update --dump-sql2# [OK] No Metadata Classes to process.

The message looks like success, but it means the opposite. The mappings: block therefore has to be rewritten following the aggregate chapter before the first migration is created. The second step is DATABASE_URL in .env. The recipe sets up PostgreSQL, so with SQLite or MySQL the connection points at nothing:

ini .env.local
1# SQLite is enough for all the samples in the book and needs no running server2DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"

The test adapter switches from the sagas chapter, by contrast, belong in the versioned .env, not in .env.local. Kernel tests do not read .env.local, so the first test that touches the payment gateway would fail with EnvNotFoundException:

ini .env
1PAYMENT_FAILS=02STOCK_FAILS=0
bash terminal
1# doctrine:database:create is not needed with SQLite and ends with the error2# “getCreateDatabaseSQL is not supported by platform” – the driver creates3# the file itself on the first connection.4 5# Migrations first have to be generated from the mapping. Without this step,6# migrate ends with “there are no registered migrations.”7php bin/console doctrine:migrations:diff8php bin/console doctrine:migrations:migrate

migrations:diff does not generate the read model tables: the ORM does not know about them, and schema_filter deliberately excludes them from the schema comparison. You therefore write the migration for order_dashboard, reporting_orders, and order_audit_log by hand, following the DDL in the chapters on CQRS, on the Outbox, and on authorization.

The tests from the CQRS chapter run against a real database, so they need more preparation. The saga test from Sagas and Process Managers gets by with an in-memory repository, but it needs PHPUnit as well. PHPUnit is deliberately missing from the list above, because not everyone needs it:

bash terminal
1composer require --dev symfony/test-pack

One detail remains that costs half an hour of searching: .env.local is not loaded in the test environment. Kernel tests therefore pick up DATABASE_URL from .env, that is, the PostgreSQL from the recipe, and fail with Connection refused. The value belongs in .env.test.local:

ini .env.test.local
1DATABASE_URL="sqlite:///%kernel.project_dir%/var/test.db"

The Symfony 8 recipe turns on stateless CSRF protection (csrf_protection.stateless_token_ids). The forms in the book pass it without a single line of JavaScript: SameOriginCsrfTokenManager accepts a request whose Origin or Sec-Fetch-Site: same-origin matches, and the browser sends those on a regular form submission. The protection still works; a cross-origin request does not get through. You can switch to the classic mode with a token in the session by deleting the stateless_token_ids key from config/packages/csrf.yaml, but there is no need to.

The test database is a different file and needs its own migration, otherwise the first kernel test fails with no such table: users:

bash terminal
1php bin/console doctrine:migrations:migrate --no-interaction --env=test

23.00 The application needs two running processes#

This step is the easiest to overlook, because leaving it out breaks nothing. After installation and starting the web server, an order goes through: POST /orders returns a redirect, a flash message reports success, and the detail page renders. After that, nothing happens.

bash terminal
1# state after submitting an order when the workers are not running2order            confirmed  (saga_in_progress = 1)3order_dashboard  0 rows4reporting_orders 0 rows5outbox           1 row in the pending state

The order stays locked by a process that never started, so it cannot even be cancelled – isCancellable() returns false and the template does not offer the button. No exception is thrown anywhere, and there is nothing in the log.

Two continuously running processes are missing. The relay picks rows from the outbox and sends them to the bus; the worker processes them:

bash terminal – two separate terminals
1php bin/console app:outbox:dispatch --time-limit=36002php bin/console messenger:consume async_events async_commands --time-limit=3600

In production, supervisord or systemd keeps them running, as the Outbox chapter describes. During development, two terminal windows are enough. Without them, the application only collects orders that nobody processes.

23.01 Example: an e-commerce application#

A slice of an online store covering the cart and orders has two Bounded Contexts: Cart (a purchase in progress) and Ordering (a confirmed transaction). The domain event CartCheckedOut passes between them, and the Ordering context reacts to it by creating an Order aggregate.

FIG. 23.1-A Online store: the Cart and Ordering Bounded Contexts

Project structure

bash src/ structure
1src/2├── Cart/                      # Bounded Context: Cart3│   ├── Domain/4│   │   ├── Model/Cart.php          # Aggregate Root5│   │   ├── Model/CartItem.php6│   │   ├── ValueObject/CartId.php, ProductId.php, UserId.php7│   │   ├── Event/ItemAddedToCart.php, CartCheckedOut.php, CheckedOutItem.php8│   │   ├── Exception/EmptyCartException.php, CartAlreadyCheckedOutException.php9│   │   └── Repository/CartRepository.php, ProductRepository.php10│   ├── Infrastructure/Repository/DoctrineCartRepository.php11│   ├── AddItem/{Command, Controller}/  # Feature slice12│   ├── GetCart/{Query, ViewModel}/     # Feature slice13│   └── Checkout/Controller/             # Feature slice14├── Ordering/                  # Bounded Context: Orders (layers)15│   ├── Domain/Model/Order.php          # Aggregate Root16│   ├── Domain/ValueObject/OrderId.php, CustomerId.php, ProductId.php17│   ├── Domain/Event/OrderPlaced.php18│   ├── Application/Command/PlaceOrder.php19│   ├── Application/Handler/PlaceOrderHandler.php20│   ├── Application/Listener/PlaceOrderOnCartCheckedOut.php21│   └── Infrastructure/Http/PlaceOrderController.php22└── SharedKernel/Domain/{Money.php, Exception/DomainException.php}

Cart is split into feature slices. Ordering keeps the Domain, Application, and Infrastructure layers as in the rest of the book, so the command and the handler can be taken over from the Outbox chapter without changing the namespace.

The Cart aggregate

The Cart aggregate guards three rules: for the same productId, it increases the quantity of the existing item instead of adding a new one, an empty cart never becomes an order, and a cart is checked out only once. Both methods that carry invariants have a full body; the rest stays a skeleton:

php src/Cart/Domain/Model/Cart.php (skeleton)
1final class Cart extends AggregateRoot2{3    public readonly CartId $id;4    public readonly UserId $userId;5    /** @var Collection<int, CartItem> */6    private Collection $items;7    private bool $checkedOut = false;8 9    public static function open(CartId $id, UserId $userId): self { /* ... */ }10 11    public function addItem(ProductId $productId, int $quantity, Money $unitPrice): void12    {13        // INVARIANT: one item per product – quantities add up, the line is not duplicated.14        $existing = $this->findItem($productId);15 16        if ($existing !== null) {17            $existing->increaseQuantity($quantity);18        } else {19            $this->items->add(new CartItem($this->id, $productId, $quantity, $unitPrice));20        }21 22        $this->record(new ItemAddedToCart($this->id, $productId, $quantity));23    }24 25    public function checkout(): void26    {27        // INVARIANT: an empty cart does not produce an order.28        if ($this->items->isEmpty()) {29            throw EmptyCartException::withId($this->id);30        }31 32        // INVARIANT: a cart is checked out once. Without this, a double click or33        // a retry would produce two events, and therefore two orders.34        if ($this->checkedOut) {35            throw CartAlreadyCheckedOutException::withId($this->id);36        }37 38        $this->checkedOut = true;39 40        $this->record(new CartCheckedOut(41            $this->id,42            $this->userId,43            array_map(CheckedOutItem::fromCartItem(...), $this->items->toArray()),44            new \DateTimeImmutable(),45        ));46    }47 48    public function removeItem(ProductId $productId): void { /* ... */ }49    public function totalAmount(): Money { /* sum over items */ }50    private function findItem(ProductId $productId): ?CartItem { /* ... */ }51}

The full implementation, including the Doctrine mapping (#[ORM\OneToMany], cascade, orphanRemoval, an optimistic lock via #[ORM\Version]), is shown in Aggregate Design and Implementation in Symfony 8.

Command handler: AddItemToCart

A thin application handler: it loads the aggregate, delegates the domain logic, and saves.

php src/Cart/AddItem/Command/AddItemToCartHandler.php (skeleton)
1#[AsMessageHandler(bus: 'command.bus')]2final readonly class AddItemToCartHandler3{4    public function __construct(5        private CartRepository $carts,6        private ProductRepository $products,7    ) {}8 9    public function __invoke(AddItemToCart $command): void10    {11        $cart = $this->carts->get(new CartId($command->cartId));12        $product = $this->products->get(new ProductId($command->productId));13 14        $cart->addItem($product->id, $command->quantity, $product->price);15 16        $this->carts->save($cart);17    }18}

The ProductRepository interface exists in the Cart context only as a port. Its implementation is deliberately absent from the structure: it comes from the Catalog context, which the example leaves out.

The full CQRS implementation with validation, authorization, and the outbox is shown in the CQRS and Outbox Pattern chapters.

From cart to order

Checkout is the only place where the two contexts meet. Cart knows nothing about orders; it records an event, and for Cart the work ends there. The event carries a copy of the data, not the cart's entities, because the contexts know each other only through identifiers and values.

php src/Cart/Domain/Event/CartCheckedOut.php
1<?php2 3declare(strict_types=1);4 5namespace App\Cart\Domain\Event;6 7use App\Cart\Domain\ValueObject\CartId;8use App\Cart\Domain\ValueObject\UserId;9 10final readonly class CartCheckedOut11{12    /** @param list<CheckedOutItem> $items */13    public function __construct(14        public CartId $cartId,15        public UserId $userId,16        public array $items,17        public \DateTimeImmutable $occurredAt,18    ) {}19}

On the other side of the boundary stands a listener of the Ordering context. It translates the foreign vocabulary into a command of its own context: the cart's UserId becomes the order's customerId.

php src/Ordering/Application/Listener/PlaceOrderOnCartCheckedOut.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Listener;6 7use App\Cart\Domain\Event\CartCheckedOut;8use App\Cart\Domain\Event\CheckedOutItem;9use App\Ordering\Application\Command\PlaceOrder;10use Symfony\Component\DependencyInjection\Attribute\Target;11use Symfony\Component\Messenger\Attribute\AsMessageHandler;12use Symfony\Component\Messenger\MessageBusInterface;13 14#[AsMessageHandler(bus: 'event.bus')]15final readonly class PlaceOrderOnCartCheckedOut16{17    public function __construct(18        #[Target('command.bus')]19        private MessageBusInterface $commandBus,20    ) {}21 22    public function __invoke(CartCheckedOut $event): void23    {24        // The listener itself saves nothing. event.bus has no doctrine_transaction,25        // so save() without a flush would write nothing and nobody would pick up26        // OrderPlaced. The command handler takes care of the transaction, confirmation, and outbox.27        $this->commandBus->dispatch(new PlaceOrder(28            customerId: $event->userId->value,29            items: array_map(30                static fn (CheckedOutItem $item): array => [31                    'productId' => $item->productId->value,32                    'quantity' => $item->quantity,33                    'unitPriceInCents' => $item->unitPrice->amountInCents,34                ],35                $event->items,36            ),37        ));38    }39}

The PlaceOrder command is the same one as in the Outbox Pattern chapter, including the FQCN App\Ordering\Application\Command\PlaceOrder. Messenger looks up the handler by class, so a copy in a different namespace would end in NoHandlerForMessageException. The canonical handler creates the order via placeWithItems(), confirms it, and stores the integration event in the outbox in the same transaction.

For brevity, the listener subscribes directly to the domain event of the Cart context. In production, Cart would publish an integration event, the way Ordering does with OrderPlacedIntegrationEvent. At the latest when the Ordering context becomes a separate service, it needs its own integration DTO populated from the message payload. The reasons are covered in DDD and Microservices. Reliable delivery between contexts is not something the bus provides by itself; that is the job of the Outbox Pattern.

23.02 Example: a blog#

The blog is a single Bounded Context with a single aggregate, Post, and slices for creating a post, adding a comment, the listing, and the detail page. Comment is an entity inside the aggregate.

FIG. 23.2-A Blog: domain model and feature slices

Project structure

bash src/ structure
1src/2└── Blog/                      # Bounded Context: Blog3    ├── Domain/4    │   ├── Model/Post.php           # Aggregate Root5    │   ├── Model/Comment.php6    │   ├── ValueObject/PostId.php, CommentId.php, AuthorId.php7    │   ├── Event/PostCreated.php, CommentAdded.php8    │   ├── Exception/CommentsClosedException.php, InvalidPostTitleException.php,9    │   │   EmptyPostContentException.php10    │   └── Repository/PostRepository.php11    ├── Infrastructure/Repository/DoctrinePostRepository.php12    ├── CreatePost/{Command, Controller}/13    ├── AddComment/{Command, Controller}/14    ├── GetPost/{Query, Controller, ViewModel}/15    └── GetPosts/{Query, Controller, ViewModel}/

The Post aggregate

The Post aggregate comes into existence through the named constructor create(). It enforces the invariants (a title of 3–255 characters, non-empty content), and the new instance records PostCreated. The constructor stays private and does not record the event, otherwise reconstitution from the database would emit it again.

php src/Blog/Domain/Model/Post.php (skeleton)
1final class Post extends AggregateRoot2{3    /** @var Collection<int, Comment> */4    private Collection $comments;5    private bool $commentsClosed = false;6 7    private function __construct(8        public readonly PostId $id,9        private string $title,10        private string $content,11        public readonly AuthorId $authorId,12        public readonly \DateTimeImmutable $createdAt,13    ) {14        $this->comments = new ArrayCollection();15    }16 17    public static function create(PostId $id, string $title, string $content, AuthorId $authorId): self18    {19        // INVARIANT: the title has 3–255 characters and the content is not empty.20        $titleLength = mb_strlen($title);21        if ($titleLength < 3 || $titleLength > 255) {22            throw InvalidPostTitleException::lengthOutOfRange($titleLength);23        }24        if (trim($content) === '') {25            throw EmptyPostContentException::forPost($id);26        }27 28        $post = new self($id, $title, $content, $authorId, new \DateTimeImmutable());29        $post->record(new PostCreated($id, $title, $authorId));30 31        return $post;32    }33 34    public function addComment(CommentId $id, AuthorId $authorId, string $text): void35    {36        // INVARIANT: no comment is added to a closed discussion.37        if ($this->commentsClosed) {38            throw CommentsClosedException::forPost($this->id);39        }40 41        $this->comments->add(new Comment($id, $this->id, $authorId, $text));42        $this->record(new CommentAdded($this->id, $id, $authorId));43    }44 45    public function closeComments(): void { /* ... */ }46    public function updateTitle(string $newTitle): void { /* ... */ }47    public function updateContent(string $newContent): void { /* ... */ }48}

Comment is an inner entity of the aggregate, not a separate aggregate root. It is created only through Post::addComment(), so the “closed discussion” invariant cannot be bypassed. The aggregate boundary and its consequences for concurrent writes are covered in Aggregate Design.

Command handler: CreatePost

php src/Blog/CreatePost/Command/CreatePostHandler.php (skeleton)
1#[AsMessageHandler(bus: 'command.bus')]2final readonly class CreatePostHandler3{4    public function __construct(private PostRepository $posts) {}5 6    public function __invoke(CreatePost $command): void7    {8        $post = Post::create(9            new PostId($command->postId),10            $command->title,11            $command->content,12            new AuthorId($command->authorId),13        );14 15        $this->posts->save($post);16    }17}

The handler returns nothing, and the post identifier arrives in the command. The controller generates it via PostId::generate() before the dispatch. Returning the ID from the handler via HandledStamp is the other option, but with an asynchronous transport the result never reaches the caller; the two variants are compared in the Should commands return a value? section of CQRS.

The read model for the post listing belongs outside the write repository: pagination, sorting by date, projections from events. It is covered in ViewModels and read models and in Read Models, Projections, and Performance.

23.03 Example: user management#

The UserManagement Bounded Context holds a single aggregate, User, and three slices: registration, authentication, and profile. The aggregate integrates with Symfony Security (it implements UserInterface).

FIG. 23.3-A User management: feature slices

Project structure

bash src/ structure
1src/2└── UserManagement/            # Bounded Context: User management3    ├── Domain/4    │   ├── Model/User.php           # Aggregate Root5    │   ├── ValueObject/UserId.php, UserName.php, Email.php, HashedPassword.php6    │   ├── Event/UserRegistered.php7    │   ├── Exception/DuplicateEmailException.php8    │   └── Repository/UserRepository.php9    ├── Infrastructure/Repository/DoctrineUserRepository.php10    ├── Registration/{Command, Controller}/11    ├── Authentication/Controller/12    └── Profile/{Query, Controller}/

The User aggregate

The User aggregate implements Symfony's UserInterface for the Security component. The Email value object validates the format in its constructor, and HashedPassword encapsulates the hashing logic.

php src/UserManagement/Domain/Model/User.php (skeleton, UserInterface variant)
1final class User extends AggregateRoot implements UserInterface, PasswordAuthenticatedUserInterface2{3    private function __construct(4        public readonly UserId $id,5        private UserName $name,6        private Email $email,7        private HashedPassword $hashedPassword,8        public readonly \DateTimeImmutable $createdAt,9    ) {10    }11 12    public static function register(UserId $id, UserName $name, Email $email, HashedPassword $hashedPassword): self13    {14        $user = new self($id, $name, $email, $hashedPassword, new \DateTimeImmutable());15        $user->record(new UserRegistered($id, $email, $user->createdAt));16 17        return $user;18    }19 20    public function changeEmail(Email $newEmail): void { /* invariant: new != old */ }21    public function rename(UserName $newName): void { /* ... */ }22 23    // UserInterface – Symfony 8 removed eraseCredentials() from the interface24    public function getRoles(): array { return ['ROLE_USER']; }25    public function getUserIdentifier(): string { return $this->email->value; }26    public function getPassword(): ?string { return $this->hashedPassword->value; }27}

This is a simplified variant of the reference implementation from Implementation in Symfony 8. The register() signature and the UserName, Email, and HashedPassword value objects are the same, and the UserRegistered event is recorded in the register() factory method, never in the constructor. The small example makes one compromise: UserInterface is implemented directly by the aggregate, whereas in the full architecture it belongs to an adapter in the infrastructure layer (see Authorization in DDD). final on an entity mapped by Doctrine works here, because with native lazy objects enabled (PHP 8.4, ORM 3.4+), Doctrine does not extend the entity.

The password hash should not travel into the session. The PasswordAuthenticatedUserInterface documentation offers __serialize() on the entity for this: the hash can be left out of the serialization, or replaced with a crc32c fingerprint. The second variant preserves the behavior that a password change invalidates logged-in sessions.

Command handler: RegisterUser

php src/UserManagement/Registration/Command/RegisterUserHandler.php (skeleton)
1#[AsMessageHandler(bus: 'command.bus')]2final readonly class RegisterUserHandler3{4    public function __construct(5        private UserRepository $users,6        private EntityManagerInterface $em,7    ) {}8 9    public function __invoke(RegisterUser $command): void10    {11        // Input normalization (trim, lowercase) belongs in fromUserInput();12        // the Email constructor only validates.13        $email = Email::fromUserInput($command->email);14 15        $user = User::register(16            UserId::generate(),17            new UserName($command->name),18            $email,19            HashedPassword::fromPlainText($command->password),20        );21 22        try {23            $this->users->save($user);24            // Flush manually: the unique constraint is evaluated only here, and the translation25            // into a domain exception has to happen inside the try block.26            $this->em->flush();27        } catch (UniqueConstraintViolationException $e) {28            throw DuplicateEmailException::with($email, $e);29        }30    }31}

Email uniqueness is guaranteed by a database constraint, not by a findByEmail() check before the write, which concurrent registrations get around. The race condition and both layers of protection are analyzed in The race condition in the naive variant with findByEmail().

Authorization of the user after login is covered in Authorization in DDD: four layers of access, the Voter, and domain invariants.

23.04 Three projects side by side#

The examples differ in domain complexity and in the number of contexts. The comparison shows what each variant requires and where its structure hits a ceiling:

Online store Blog User management
Domain complexity Medium: invariants in the cart, the checkout → order state transition Low: title and content validation, closing the discussion under a post Low to medium: unique email, password hash, integration with Security
Number of Bounded Contexts 2 (Cart, Ordering) 1 1
Patterns used Aggregates, value objects, a domain event between contexts, CQRS, repository An aggregate with an inner entity, named constructor, CQRS slices, repository An aggregate with UserInterface, the Email and HashedPassword value objects, repository
What changes as it grows Payment, Inventory, and Shipping contexts appear; checkout becomes a process run by a saga; event publishing gets an outbox Moderation and content versioning call for a separate Comment context and a read model for listings Roles, permissions, and SSO split Identity from Profile; authorization rules move into voters
When the structure stops being enough When synchronous communication between contexts starts creating dependency chains – then fully asynchronous integration takes over As soon as an editorial and approval workflow appears, a single context with a CRUD core is no longer enough When the number of “who may do what” rules outgrows the aggregate – the rules belong in a separate authorization layer

The decision about how deep the stack goes follows from the domain, not from the technology. Strategic and tactical design at full scale (multiple contexts, CQRS, domain events, outbox) pays off where the domain carries non-trivial invariants, several teams work on the system, and its individual parts evolve at different speeds. The online store in this chapter heads that way: two contexts and an event between them are the first step, and the rest comes with growth.

The middle path covers projects like the blog or user management: an aggregate with a repository, no separate read models, and no multiple contexts. Domain rules exist and deserve encapsulation, but reading stays trivial and the team small. There is one signal for the next step: once listings start hydrating aggregates only to display them, it is time for a separate read model.

Where there are no rules at all and the application only moves data between a form and a table, DDD only costs time. Symfony forms, Doctrine entities, and generic CRUD controllers handle such a case more cheaply. The boundary between the two worlds is covered in When Not to Use DDD.

23.05 Conclusion#

All three examples follow the same chain: controller → command bus → handler → aggregate → repository → event. Variations in the number of Bounded Contexts, the number of aggregates, and the integration with Symfony Security do not change that skeleton. Domain invariants belong in the aggregate, the handler carries the application orchestration, and the repository holds the infrastructure.

The samples occupy the middle of that chain. Controllers, Doctrine mapping, and repository implementations stay in Implementation in Symfony 8, where they have room for detail.

The whole project, from Event Storming through the Context Map to read models with reconciliation, is worked through in the following Case Study.

Frequently asked questions

Why do all three examples combine vertical slices and CQRS?

A vertical slice determines how to organize code (by feature); CQRS separates reads from writes. They complement each other: each feature has its own command or query handler. A command works with an aggregate, and a query returns a ViewModel for the response. The combination repeats in the samples on purpose. The exception is the Ordering context in the online store, which keeps layers so that it matches the canonical code from the Outbox chapter; public reference projects such as CodelyTV/php-ddd-example also use a similar split by use case with a CQRS bus.

Can the structure from these examples be taken over directly into a production project?

The samples are deliberately simplified – they lack complete authentication and authorization, transactional coordination between aggregates, retry logic, and more complex domain rules. What can be taken over are the principles: separating the domain and infrastructure layers, splitting by feature, and the CQRS bus. The directory structure serves as a starting template and grows with the real needs of the project. The recommended long-term architecture is described in Implementation in Symfony 8.

Where can I find a full implementation of an aggregate with all its methods?

In the chapters Aggregate Design (a complete Order aggregate with invariants, an optimistic lock, domain events, and Doctrine mapping) and Implementation in Symfony 8 (a User aggregate with Symfony Security, custom types for value objects, a repository with the Outbox Pattern).

Why do the blog and user management have only one Bounded Context?

For a summary chapter, simpler cases with a single context are easier to follow. The online store has two contexts (Cart and Ordering) to illustrate communication between contexts through the domain event CartCheckedOut. In a real project, each of the three examples would probably have more contexts (Identity, Billing, Notifications), but that is material for the Case Study.