Chapter 09 · Architecture · Architectural Styles

Architectural Styles

DDD says what to model. An architectural style says where it belongs in the code. The chapter compares layered architecture, Hexagonal (Cockburn), Onion (Palermo), Clean (Martin), and Vertical Slice, and shows which of them to choose in Symfony 8.

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

When a team says “we're moving to DDD,” it usually means two things: we will model the domain better and we will rearrange the directory structure. The two decisions are in fact orthogonal, that is, independent of each other. Domain-Driven Design is a modeling technique; an architectural style determines how the code is organized and which way the dependencies point. DDD works in a layered architecture, in Hexagonal, Onion, Clean, and Vertical Slice alike. The reverse holds too: a hexagonal architecture built on top of an anemic CRUD model has nothing to do with DDD.

What follows is a comparison of four layer-based styles (Layered, Hexagonal, Onion, Clean) and a fifth, feature-oriented one, Vertical Slice, including what each looks like in Symfony 8. No winner comes out of it, because every style has a context in which it pays off. The decision criteria are more useful, and so are the anti-patterns that turn good theory into bad code.

09.01 Why an architectural style is not the same as DDD#

Confusion in the DDD literature most often comes from mixing up two independent decisions. The first is the modeling technique: will we use aggregates, value objects, domain events, Ubiquitous Language, and Bounded Contexts? Or will we stay with procedural CRUD, where a controller reads from the database, validates the data, and writes it back? The second is code organization: split the project by technical layers, through ports and adapters, into concentric rings, or by feature?

The two decisions can be combined freely. There are projects with a pure CRUD model in a Hexagonal architecture (ports separate HTTP from the database, but inside sits an anemic table row). Elsewhere, rich DDD aggregates live in a classic layered structure (Doctrine entities in the src/Entity directory, but with methods such as $order->confirm() and $order->cancel(), and invariants checked in the constructor). An architectural style affects testability and composition; it does not touch the modeling method.

In his original book Domain-Driven Design (2003) [1], Eric Evans devotes only one short chapter to layered architecture. The weight of the book lies in modeling. The layers in it protect the model from technical details; they are not a goal in themselves. Later authors (Vernon, Khononov, Millett & Tune) show DDD in layered, hexagonal, and feature-first styles. All of them work, provided the domain model inside has real substance.

No architectural style helps a trivial domain (CRUD over a few tables, no invariants, no state transitions), because there is nothing to protect. A rich domain that you do not separate from the framework (direct calls to the EntityManager, Symfony Request/Response objects, external HTTP clients) produces code that looks “clean” at first glance. Without the whole infrastructure, however, it cannot be tested.

The styles are ordered from the simplest to the most complex; each one comes with its Symfony form, suitable and unsuitable uses, and its most common anti-pattern.

09.02 Layered (classic layered architecture)#

In Patterns of Enterprise Application Architecture (2002) [2], Martin Fowler works with three main layers: Presentation, Domain (domain logic), and Data Source. In Domain-Driven Design (2003), Eric Evans works with four layers: User Interface (Presentation), Application, Domain, and Infrastructure. He insists on the rule that a layer may depend only on the layers below it, never upward. Later DDD literature adopted this division.

The four standard layers

  • Presentation Layer – interaction with the outside world (HTTP controllers, CLI commands, GraphQL resolvers). In Symfony, these are the classes in src/Controller/.
  • Application Layer – use case orchestration, transactions, DTO mapping. Thin classes, no domain logic; that lives in the domain. In Symfony, they usually sit in src/Service/ or src/Application/.
  • Domain Layer – aggregates, entities, value objects, domain services, repository interfaces. No dependencies on the framework. In Symfony, usually src/Entity/ + src/Domain/.
  • Infrastructure Layer – Doctrine repository implementations, email gateways, HTTP clients, Messenger transports. In Symfony, src/Repository/ + src/Infrastructure/.

The structures later in the chapter work with only three directories (Domain/, Application/, Infrastructure/) and place controllers in the infrastructure. That is how Matthias Noback described the layers for PHP, and the convention caught on. Of Evans's four layers, UI thereby merges with infrastructure; the rule about the direction of dependencies stays unchanged.

A typical Symfony structure

bash src/ (Symfony Layered convention)
1src/2├── Controller/                      # Presentation3│   ├── OrderController.php4│   └── CustomerController.php5├── Service/                          # Application6│   ├── OrderService.php7│   └── CustomerService.php8├── Entity/                           # Domain (with Doctrine attributes → leak)9│   ├── Order.php10│   ├── OrderLine.php11│   └── Customer.php12├── Repository/                       # Infrastructure13│   ├── OrderRepository.php14│   └── CustomerRepository.php15└── Form/                             # Presentation (input)16    └── OrderType.php

The Controller/, Entity/, and Repository/ directories match the default Symfony skeleton. MakerBundle fills them: make:controller creates a controller, make:entity an entity together with its repository, make:form a form. A junior team finds its way around the structure without explanation. Every file has its place, and a new use case means a controller, a service, an entity, and a repository.

An example domain entity in layered DDD

php src/Entity/Order.php
1<?php2 3declare(strict_types=1);4 5namespace App\Entity;6 7use App\Repository\OrderRepository;8use Doctrine\Common\Collections\ArrayCollection;9use Doctrine\Common\Collections\Collection;10use Doctrine\ORM\Mapping as ORM;11 12#[ORM\Entity(repositoryClass: OrderRepository::class)]13#[ORM\Table(name: 'orders')]14class Order15{16    #[ORM\Id]17    #[ORM\Column(type: 'string', length: 36)]18    private string $id;19 20    #[ORM\Column(type: 'string', length: 32)]21    private string $status = 'draft';22 23    #[ORM\OneToMany(mappedBy: 'order', targetEntity: OrderLine::class, cascade: ['persist'])]24    private Collection $lines;25 26    public function __construct(string $id)27    {28        $this->id = $id;29        // Without initialization, the first access to the collection fails with30        // "Typed property must not be accessed before initialization".31        $this->lines = new ArrayCollection();32    }33 34    public function id(): string35    {36        return $this->id;37    }38 39    public function status(): string40    {41        return $this->status;42    }43 44    public function confirm(): void45    {46        if ($this->status !== 'draft') {47            throw new \DomainException('Only draft orders can be confirmed.');48        }49        if ($this->lines->isEmpty()) {50            throw new \DomainException('Cannot confirm an empty order.');51        }52        $this->status = 'confirmed';53    }54 55    public function cancel(): void56    {57        if ($this->status === 'shipped') {58            throw new \DomainException('Cannot cancel a shipped order.');59        }60        $this->status = 'cancelled';61    }62}

The Order class has rich behavior (confirm(), cancel()) and checks invariants, which is solid DDD modeling. Through the #[ORM\Entity] and #[ORM\Column] attributes, however, it depends on Doctrine ORM. The rule “an empty order cannot be confirmed” thus lives in domain code that knows it is stored through Doctrine. From the point of view of Hexagonal/Onion architecture, this is a domain leak: the domain class imports a library from Infrastructure and carries its metadata. Layered accepts this compromise pragmatically, and the book treats it as the default choice (discussed in the Implementation in Symfony 8 chapter). Hexagonal insists on separation through the Persisted Object Pattern. The bare \DomainException stands here in the same spirit. The rest of the book uses named exceptions such as InvalidOrderStateTransitionException; the Layered example stays with the shortcut to show what the style actually requires and what it does not.

When Layered fits

Layered pays off where predictability is worth more than isolation. For a junior team, the Symfony skeleton and the make:* commands provide a structure it does not have to invent. In an application with ten to fifty endpoints, an investment in ports and adapters does not pay back. If the product has a short horizon (MVP, prototype, internal tool), vendor lock-in to Doctrine is a theoretical risk, because the migration never comes. For a team fluent in Symfony, an extra layer would only slow the work down without solving any of its real problems.

When Layered stops being enough

  • The domain model needs tests without a database. Tests through Doctrine fixtures are slow and brittle.
  • You plan to replace the persistence layer (e.g., PostgreSQL → DynamoDB, or Doctrine → hand-written SQL). Removing the Doctrine attributes from the entities then means an extensive migration.
  • Domain rules need to live in one place. In the layered model, they tend to scatter across controllers, the service layer, and entities.
  • The application has several input channels (HTTP API, CLI, message queue, GraphQL). An Application Service written around the HTTP Request object fits CLI input badly.

A typical Layered controller in Symfony

Orchestration code in a Layered architecture: the controller loads a Doctrine entity from the repository and passes it to an Application Service, which calls the domain method and flushes the changes. No ports, no DTO mappers, and no explicit interfaces between layers.

php src/Controller/OrderController.php
1<?php2 3declare(strict_types=1);4 5namespace App\Controller;6 7use App\Repository\OrderRepository;8use App\Service\OrderService;9use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;10use Symfony\Component\HttpFoundation\JsonResponse;11use Symfony\Component\HttpFoundation\Request;12use Symfony\Component\Routing\Attribute\Route;13 14final class OrderController extends AbstractController15{16    public function __construct(17        private readonly OrderRepository $repository,18        private readonly OrderService $service,19    ) {20    }21 22    #[Route('/orders/{id}/confirm', methods: ['POST'])]23    public function confirm(string $id): JsonResponse24    {25        $order = $this->repository->find($id);26        if ($order === null) {27            throw $this->createNotFoundException("Order {$id} not found.");28        }29 30        $this->service->confirm($order);31 32        return new JsonResponse(['status' => $order->status()]);33    }34}

The code is readable, short, and typical for Symfony. You pay the price in tests. You test OrderController::confirm() either through WebTestCase with a full application boot, or with mocks of both OrderRepository and OrderService. In a Hexagonal structure, calling the use case without the controller is enough.

09.03 Hexagonal Architecture (Ports & Adapters, Cockburn 2005)#

In the classic three-layer structure (UI / Logic / Database), tests of application logic necessarily went either through the UI or through the database. That bothered Alistair Cockburn, and in 2005, in the article Hexagonal Architecture (Ports and Adapters) [3], he proposed a different arrangement. In it, the application core (the domain) communicates with the outside world exclusively through well-defined ports (interfaces). Concrete technologies (HTTP, SQL, email, message queues) implement these ports as adapters.

The number six in the hexagon means nothing. Cockburn chose it so that whoever draws the diagram has enough room around the core for ports and adapters and is not bound by a one-dimensional layered scheme [3]. An octagon or a triangle would have served equally well.

Since 2024, the pattern also has a book: Hexagonal Architecture Explained, which Cockburn wrote with Juan Manuel Garrido de Paz. Among other things, the book was a response to interpretations that had drifted from the original.

Two types of ports

  • Driving (inbound, primary) port – what the application can do. It defines how the outside world calls the domain. In DDD terms, it corresponds to an Application Service or Use Case interface. Examples: ForPlacingOrders, ForCancellingOrders, ForGettingOrderHistory. The For prefix follows Cockburn's convention: a port is named after the purpose of the conversation. Thanks to it, the port names do not collide with the PlaceOrder command from the CQRS chapter.
  • Driven (outbound, secondary) port – what the application needs. It defines the interface for external dependencies. In DDD, these are repository interfaces, gateways to external systems, and domain event publishers. Examples: OrderRepository, EmailSender, EventPublisher.

Adapters implement ports: a driving adapter (Symfony controller, CLI command, Messenger handler) calls an inbound port; a driven adapter (Doctrine repository, SMTP mailer, RabbitMQ publisher) implements an outbound port. The domain itself knows no adapter and no concrete technology.

How many ports make sense

In the original, a port is not a synonym for the interface of a single dependency. Cockburn defines it as a “purposeful conversation,” a thematic channel into which several adapters for different technologies typically plug [3]. On their number, he adds that the extreme variant “a port for every use case” leads to hundreds of ports in a larger application. He himself leans toward two to four. In his sample system, he names four: the weather data feed, the administrator, notifications to subscribers, and the subscriber database.

PHP practice goes a different way. Repositories, mailers, and event publishers each get their own interface, one to one, because that matches how autowiring and test doubles are written in Symfony. The rest of this guide uses this finer granularity too. It is not Cockburn's definition, though: for him, one port covers the whole conversation, which PHP practice splits into several interfaces.

One boundary holds in both readings. In a 2020 interview, Cockburn names as the main mistake in practice “one technology per port, or a port per technology” [4]. This defeats the purpose of a port, which is replacing the technology without changing the core. A RedisOrderCache interface violates the pattern; OrderCache with a Redis adapter and an in-memory adapter for tests does not.

The mechanism beneath ports was named Configurable Dependency by Gerard Meszaros in a 2011 conversation with Cockburn. The concrete implementation of such a dependency is decided only when the application is assembled from the outside [4]. In Symfony, the Service Container plays this role.

A Symfony structure following Hexagonal

bash src/ (Symfony Hexagonal structure)
1src/2├── Ordering/                           # Bounded Context3│   ├── Domain/                         # Domain core (no framework deps)4│   │   ├── Model/5│   │   │   ├── Order.php               # Aggregate Root – PLAIN PHP6│   │   │   └── OrderLine.php7│   │   ├── ValueObject/8│   │   │   └── OrderId.php9│   │   ├── Event/10│   │   │   └── OrderConfirmed.php11│   │   └── Port/                       # Outbound ports (interfaces)12│   │       ├── OrderRepository.php13│   │       └── EventPublisher.php14│   ├── Application/                    # Inbound ports + use cases15│   │   ├── UseCase/16│   │   │   ├── ForPlacingOrders.php    # Inbound port (interface)17│   │   │   └── PlaceOrderHandler.php   # Use case implementation18│   │   └── Dto/19│   │       └── PlaceOrderInput.php20│   └── Infrastructure/                 # Adapters (driving + driven)21│       ├── Http/                       # Driving adapter22│       │   └── PlaceOrderController.php23│       ├── Cli/                        # Driving adapter24│       │   └── PlaceOrderCommand.php25│       └── Persistence/                # Driven adapter26│           ├── DoctrineOrderRepository.php27│           ├── OrderMapper.php         # Translation domain ↔ ORM28│           └── OrderOrmEntity.php      # Doctrine entity for persistence29└── SharedKernel/30    └── Domain/31        └── DomainException.php

The structure implies the following:

  • The Domain/ directory contains no imports from Doctrine, Twig, or any other library, only plain PHP and its own types. The only part of Symfony allowed is the Symfony\Component\Uid component, through which OrderId::generate() creates the identity.
  • The repository interface (OrderRepository) lives in Domain/Port/; its implementation (DoctrineOrderRepository) lives in Infrastructure/Persistence/. The domain depends on the interface, the infrastructure implements it.
  • The domain entity (Order) is not a Doctrine entity. Mapping is handled by a separate OrderOrmEntity + mapper (the Persisted Object Pattern), so the domain stays clean. Note: Hexagonal Architecture insists on this separation. The more pragmatic approach, which the rest of the guide uses as the default, allows attributes directly on the aggregate (see the mapping decision).
  • Input into the application passes through an inbound port (ForPlacingOrders). The HTTP controller and the CLI command do not depend on the domain directly, but on this port.

You will not find the split of the core into Domain/ and Application/ in the original. Cockburn describes only the inside and the outside of the hexagon; according to Garrido de Paz, the division into an application layer and a domain layer is a DDD topic, not a topic of hexagonal architecture [4]. The structure above is therefore a composition of two patterns, not one.

Example: an outbound port and its adapter

php src/Ordering/Domain/Port/OrderRepository.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Port;6 7use App\Ordering\Domain\Exception\OrderNotFoundException;8use App\Ordering\Domain\Model\Order;9use App\Ordering\Domain\ValueObject\OrderId;10 11// Port/ is the hexagonal name for the directory the rest of the book calls Repository/.12interface OrderRepository13{14    /** @throws OrderNotFoundException */15    public function get(OrderId $id): Order;16 17    public function save(Order $order): void;18 19    // A customer's list of orders does not belong here: screens are served20    // by a read model (CQRS chapter), the repository loads the aggregate for a change.21}
php src/Ordering/Infrastructure/Persistence/DoctrineOrderRepository.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Persistence;6 7use App\Ordering\Domain\Exception\OrderNotFoundException;8use App\Ordering\Domain\Model\Order;9use App\Ordering\Domain\Port\OrderRepository;10use App\Ordering\Domain\ValueObject\OrderId;11use Doctrine\ORM\EntityManagerInterface;12 13final class DoctrineOrderRepository implements OrderRepository14{15    public function __construct(16        private readonly EntityManagerInterface $em,17        private readonly OrderMapper $mapper,18    ) {19    }20 21    public function get(OrderId $id): Order22    {23        $orm = $this->em->find(OrderOrmEntity::class, $id->value)24            ?? throw OrderNotFoundException::withId($id);25 26        return $this->mapper->toDomain($orm);27    }28 29    public function save(Order $order): void30    {31        // The example covers insert. On update, a real implementation first32        // finds the existing OrderOrmEntity via find() and overwrites its fields –33        // persist() of a new instance would end in a primary key collision.34        //35        // The flush is here because the controller calls the port directly. Once36        // commands go through a command bus with the doctrine_transaction middleware,37        // that middleware owns the transaction and the flush disappears from here.38        // Without one or the other, the API returns 201 and nothing stays in the database.39        $orm = $this->mapper->toOrm($order);40        $this->em->persist($orm);41        $this->em->flush();42    }43}

The domain class Order is plain PHP without a single Doctrine attribute. OrderOrmEntity is a separate persistence class with Doctrine mapping, and OrderMapper translates between the two. The price is a duplicate class and hand-written mapping. In return, the domain model can be tested in memory without a database, and a change of the persistence layer does not affect it.

Example: an inbound port and its HTTP adapter

A driving (inbound) port defines what the application can do. In DDD terms, it is the contract of an Application Service. In Symfony 8, it usually maps to a CQRS command/query handler (covered in detail in the CQRS chapter) dispatched through a Messenger bus. The port can also be written explicitly as an interface with a single handler as its implementation.

php src/Ordering/Application/UseCase/ForPlacingOrders.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\UseCase;6 7use App\Ordering\Application\Dto\PlaceOrderInput;8use App\Ordering\Application\Dto\PlaceOrderOutput;9 10/**11 * Inbound port (driving) – the contract of the application capability12 * “place an order”. The HTTP adapter, the CLI command, and tests13 * all call through this port; the concrete implementation is in the handler.14 */15interface ForPlacingOrders16{17    public function handle(PlaceOrderInput $input): PlaceOrderOutput;18}

Both DTOs are ordinary immutable structures without behavior. With them, the port delimits what goes in and what comes out:

php src/Ordering/Application/Dto/PlaceOrderInput.php + PlaceOrderOutput.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\Dto;6 7final readonly class PlaceOrderInput8{9    /** @param list<array{productId: string, quantity: int, unitPriceInCents: int}> $items */10    public function __construct(11        public string $customerId,12        public array $items,13    ) {}14}15 16final readonly class PlaceOrderOutput17{18    public function __construct(19        public string $orderId,20        public string $status,21    ) {}22}

The HTTP adapter does not know the concrete handler class, only the port interface. The container binds the port to the implementation (see the Symfony Service Container and autowiring section below). In tests, the handler can therefore be swapped for a fake without the whole application layer.

php src/Ordering/Infrastructure/Http/PlaceOrderController.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Http;6 7use App\Ordering\Application\Dto\PlaceOrderInput;8use App\Ordering\Application\UseCase\ForPlacingOrders;9use Symfony\Component\HttpFoundation\JsonResponse;10use Symfony\Component\HttpFoundation\Request;11use Symfony\Component\Routing\Attribute\Route;12 13final class PlaceOrderController14{15    public function __construct(16        private readonly ForPlacingOrders $useCase,17    ) {18    }19 20    #[Route('/api/orders', methods: ['POST'])]21    public function __invoke(Request $request): JsonResponse22    {23        $payload = json_decode($request->getContent(), true, flags: JSON_THROW_ON_ERROR);24 25        $input = new PlaceOrderInput(26            customerId: $payload['customerId'],27            items: $payload['items'],28        );29 30        $output = $this->useCase->handle($input);31 32        return new JsonResponse([33            'orderId' => $output->orderId,34            'status' => $output->status,35        ], 201);36    }37}

Symfony Service Container and autowiring

Symfony autowiring fills in dependencies by type. For interfaces, the container manages on its own if, while loading services.yaml, it discovers an interface and exactly one implementation of it. It then creates the alias automatically. In the hexagonal structure above, both OrderRepository and DoctrineOrderRepository lie under src/, so a type-hint on the port works without a single line of configuration.

A manual alias is needed in two situations. Either there is more than one implementation, or the directory with the interface or the implementation does not fall under resource, typically because of an exclusion (see Per-context configuration in Symfony 8). An alias written even where it would arise by itself is not a mistake: it documents the choice of the default adapter. The first option is an entry in config/services.yaml:

yaml config/services.yaml (excerpt: port alias)
1services:2    _defaults:3        autowire: true4        autoconfigure: true5 6    App\:7        resource: '../src/'8 9    # Explicit binding of the port to the default adapter10    App\Ordering\Domain\Port\OrderRepository:11        alias: App\Ordering\Infrastructure\Persistence\DoctrineOrderRepository12 13    # Can be overridden for tests in config/services_test.yaml

The second option is the #[AsAlias] attribute directly on the implementation. The alias then lives in the Infrastructure layer, where it belongs:

php src/Ordering/Infrastructure/Persistence/DoctrineOrderRepository.php (with AsAlias)
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Persistence;6 7use App\Ordering\Domain\Port\OrderRepository;8use Symfony\Component\DependencyInjection\Attribute\AsAlias;9 10#[AsAlias(id: OrderRepository::class)]11final class DoctrineOrderRepository implements OrderRepository12{13    // ... see the implementation above14}

The use case in the Application layer then declares its dependency with a plain type-hint on the domain interface and does not know that a Doctrine adapter exists:

php src/Ordering/Application/UseCase/PlaceOrderHandler.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Application\UseCase;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\Port\OrderRepository;9use App\Ordering\Domain\ValueObject\CustomerId;10use App\Ordering\Domain\ValueObject\OrderId;11use App\Ordering\Domain\ValueObject\ProductId;12use App\Ordering\Application\Dto\PlaceOrderInput;13use App\Ordering\Application\Dto\PlaceOrderOutput;14use App\SharedKernel\Domain\Currency;15use App\SharedKernel\Domain\Money;16 17final class PlaceOrderHandler implements ForPlacingOrders18{19    public function __construct(20        private readonly OrderRepository $orders,21    ) {22    }23 24    public function handle(PlaceOrderInput $input): PlaceOrderOutput25    {26        // The DTO carries primitives from the HTTP layer; converting them to value objects27        // belongs here, in the application layer. The domain does not accept primitives.28        $order = Order::place(29            OrderId::generate(),30            CustomerId::fromString($input->customerId),31        );32 33        foreach ($input->items as $item) {34            $order->addItem(35                ProductId::fromString($item['productId']),36                $item['quantity'],37                new Money($item['unitPriceInCents'], Currency::CZK),38            );39        }40 41        $this->orders->save($order);42 43        return new PlaceOrderOutput($order->id->value, $order->status->value);44    }45}

An #[Autowire(service: DoctrineOrderRepository::class)] attribute directly in the handler's constructor is an anti-pattern in the Application layer. It requires importing an Infrastructure class and thereby violates the Dependency Rule that the whole structure protects. The use case would know the concrete adapter, and swapping the implementation (a test InMemoryOrderRepository) would mean touching application code instead of configuration. The alias belongs in services.yaml or on the implementation, never in the inner layers.

As soon as a port has more than one implementation, the automatic alias disappears and the container reports an ambiguity. The default adapter is then set by an alias, and the second implementation becomes available through a named autowiring alias:

yaml config/services.yaml (excerpt: named alias)
1services:2    # Default adapter of the port3    App\Ordering\Domain\Port\OrderRepository:4        alias: App\Ordering\Infrastructure\Persistence\DoctrineOrderRepository5 6    # Second implementation under a named alias7    App\Ordering\Domain\Port\OrderRepository $readOnlyOrders:8        alias: App\Ordering\Infrastructure\Persistence\ReadOnlyOrderRepository

A constructor refers to the named alias with the #[Target('readOnlyOrders')] attribute. Binding by parameter name without the attribute works too, but renaming the parameter breaks it. The test environment overrides the default alias in config/services_test.yaml, so InMemoryOrderRepository replaces the Doctrine adapter without touching application code.

A second port: the domain event publisher

The repository is the most visible outbound port, but not the only one. A second frequent candidate is publishing domain events. The application layer calls EventPublisher::publish($event) and does not care who consumes the events. The implementation can be Symfony Messenger, RabbitMQ, an in-memory dispatcher for tests, or even a no-op in simple scenarios.

php src/Ordering/Domain/Port/EventPublisher.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Port;6 7interface EventPublisher8{9    // Events are typed as `object`. The canonical AggregateRoot::record()10    // in this book requires no event base class, so binding the port11    // to a common ancestor would not let even OrderPlaced through.12    public function publish(object $event): void;13 14    /**15     * @param iterable<object> $events16     */17    public function publishAll(iterable $events): void;18}
php src/Ordering/Infrastructure/Messaging/MessengerEventPublisher.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Messaging;6 7use App\Ordering\Domain\Port\EventPublisher;8use Symfony\Component\Messenger\MessageBusInterface;9 10final class MessengerEventPublisher implements EventPublisher11{12    public function __construct(13        private readonly MessageBusInterface $eventBus,14    ) {15    }16 17    public function publish(object $event): void18    {19        $this->eventBus->dispatch($event);20    }21 22    public function publishAll(iterable $events): void23    {24        foreach ($events as $event) {25            $this->eventBus->dispatch($event);26        }27    }28}

For tests, an InMemoryEventPublisher that only collects the events into an array is enough. The test then verifies what the use case published, without Messenger, RabbitMQ, or any other infrastructure. It runs in single-digit milliseconds, not hundreds.

php tests/Ordering/Doubles/InMemoryEventPublisher.php
1<?php2 3declare(strict_types=1);4 5namespace App\Tests\Ordering\Doubles;6 7use App\Ordering\Domain\Port\EventPublisher;8 9final class InMemoryEventPublisher implements EventPublisher10{11    /** @var list<object> */12    private array $published = [];13 14    public function publish(object $event): void15    {16        $this->published[] = $event;17    }18 19    public function publishAll(iterable $events): void20    {21        foreach ($events as $event) {22            $this->publish($event);23        }24    }25 26    /**27     * @return list<object>28     */29    public function published(): array30    {31        return $this->published;32    }33}

When Hexagonal fits

  • A domain with rich behavior – where testing the domain without a database is worth the investment.
  • Several input channels. HTTP API, CLI, a Messenger consumer, and GraphQL are merely different driving adapters over the same inbound port.
  • A planned change of technology – a migration from Doctrine ORM to DBAL or to a cloud database comes down to a new adapter.
  • Applications with 50–500 endpoints – where the overhead of ports is amortized by the number of use cases.

When Hexagonal makes no sense

For CRUD over a few tables, a port, an adapter, and a mapper for every entity are overhead with no return. Hexagonal does not help a team that has not mastered Dependency Injection either; without dependency inversion, the structure is only cosmetic. And it does not pay off for a product with a short horizon either.

09.04 Onion Architecture (Palermo 2008)#

Jeffrey Palermo introduced Onion Architecture in a series of blog posts [5]. The first three parts came out in 2008, the fourth (Part 4 – After Four Years) in 2013. The pattern modifies the layered architecture: it puts the domain model at the center, and dependencies may point only inward, never outward. The name Dependency Rule was given to this rule only later, by Robert C. Martin (see Clean Architecture). The metaphor is an onion with concentric rings.

The four concentric Onion layers

  1. Domain Model (the core) – entities, value objects, aggregates, domain events. It depends on nothing, not even on the framework or persistence.
  2. Domain Services – stateless classes with domain logic that does not belong to any particular entity. They depend only on the Domain Model. In his text, Palermo places mainly the repository interfaces in the first ring around the model; the layer name comes from his diagram [5].
  3. Application Services – use case orchestration, transactions, DTO mapping. They depend on Domain Services and the Domain Model.
  4. UI / Infrastructure – controllers, repository implementations, external gateways. The outer layer depends on Application Services.

The key word is concentric. The layers are not stacked on top of each other (UI at the top, DB at the bottom) but nested: the core in the middle, the outside world around it. This removes one problem of the classic layered architecture, where Domain may depend on Infrastructure (for example, read from the database). Onion does not allow that. The core declares repositories as interfaces, and the UI/Infrastructure layer implements them.

In the After Four Years part, Palermo summed up the pattern in four tenets [6]. The application is built around an independent object model. Inner layers define interfaces, outer layers implement them. Every coupling points toward the center. And the core can be compiled and run without the infrastructure. In the same post, he rejects the common reading that it is a “DDD architecture”: in his view, Onion works with or without DDD patterns, with CQRS as well as with plain forms over data, and it can do without an IoC container too. The reading through aggregates and domain services that follows here is therefore one possible interpretation, not the definition of the pattern.

The difference from Hexagonal

Onion and Hexagonal rest on the same idea: isolate the domain and turn the dependencies inward. In a typical implementation in Symfony, they are indistinguishable. Three subtle differences:

  • Inner layering. Onion explicitly distinguishes Domain Services and Application Services as two separate layers. Hexagonal is topologically more spare – port + adapter, no inner layering.
  • Static vs. dynamic view. Onion describes layers and who depends on whom. Hexagonal takes a dynamic view: ports, adapters, and the path data takes through them.
  • Driving vs. driven ports. In Onion, the UI layer holds both the HTTP controller (driving) and the Doctrine repository (driven). From the Hexagonal point of view, that is imprecise – a driving adapter calls the application, a driven adapter is called by the domain.

If your project uses the Hexagonal vocabulary (port, adapter, driving, driven) but has two layers of services inside (Domain Service, Application Service), you are building a Hexagonal+Onion hybrid. That is fine. Hardly anyone implements a single style “purely.”

Example: Domain Service vs. Application Service

A Domain Service contains domain logic that does not belong to an aggregate (typically because it works with several aggregates at once or needs data the aggregate does not have). An Application Service is an orchestrator. It controls the transaction, loads aggregates from repositories, calls the domain logic, and publishes the outputs.

php src/Pricing/Domain/Service/PriceCalculator.php
1<?php2 3declare(strict_types=1);4 5namespace App\Pricing\Domain\Service;6 7use App\Pricing\Domain\Model\Cart;8use App\Pricing\Domain\Model\Customer;9use App\Pricing\Domain\Model\DiscountPolicy;10use App\SharedKernel\Domain\Money;11 12/**13 * Domain Service – calculating the price needs data from several aggregates14 * (Cart, Customer, DiscountPolicy). The logic is purely domain logic,15 * no framework, no persistence.16 */17final class PriceCalculator18{19    public function calculate(20        Cart $cart,21        Customer $customer,22        DiscountPolicy $policy,23    ): Money {24        $subtotal = $cart->subtotal();25        $discount = $policy->applyTo($subtotal, $customer->loyaltyTier());26        $net = $subtotal->subtract($discount);27        $vat = $net->percentage(21);28 29        return $net->add($vat);30    }31}
php src/Pricing/Application/Service/CalculateCartPrice.php
1<?php2 3declare(strict_types=1);4 5namespace App\Pricing\Application\Service;6 7use App\Pricing\Domain\Port\CartRepository;8use App\Pricing\Domain\Port\CustomerRepository;9use App\Pricing\Domain\Port\DiscountPolicyRepository;10use App\Pricing\Domain\Service\PriceCalculator;11use App\Pricing\Domain\ValueObject\CartId;12use App\SharedKernel\Domain\Money;13 14/**15 * Application Service – orchestration of the “Calculate cart price” use case.16 * The actual logic is in the Domain Service; the application layer only controls17 * the transaction and loads aggregates from repositories.18 */19final class CalculateCartPrice20{21    public function __construct(22        private readonly CartRepository $carts,23        private readonly CustomerRepository $customers,24        private readonly DiscountPolicyRepository $policies,25        private readonly PriceCalculator $calculator,26    ) {27    }28 29    public function execute(string $cartId): Money30    {31        // get() throws CartNotFoundException / CustomerNotFoundException32        // from Domain\Exception when the aggregate does not exist.33        $cart = $this->carts->get(CartId::fromString($cartId));34        $customer = $this->customers->get($cart->customerId());35 36        $policy = $this->policies->forCustomer($customer);37 38        return $this->calculator->calculate($cart, $customer, $policy);39    }40}

The two classes differ in how they access data. PriceCalculator does not know any repository and takes objects that are already loaded. CalculateCartPrice reaches them through ports and controls both loading and handing over the data. If you merge both responsibilities into one class, you lose the ability to test the price calculation in isolation, without a database.

Onion structure in Symfony

bash src/ (Symfony Onion structure)
1src/2├── Pricing/                            # Bounded Context3│   ├── Domain/                         # Inner ring (the core)4│   │   ├── Model/5│   │   │   ├── Cart.php6│   │   │   ├── Customer.php7│   │   │   └── DiscountPolicy.php8│   │   ├── ValueObject/9│   │   │   └── CartId.php10│   │   ├── Port/                       # Repository interfaces11│   │   │   ├── CartRepository.php12│   │   │   ├── CustomerRepository.php13│   │   │   └── DiscountPolicyRepository.php14│   │   └── Service/                    # 2nd ring – Domain Services15│   │       └── PriceCalculator.php16│   ├── Application/                    # 3rd ring – Application Services17│   │   └── Service/18│   │       ├── CalculateCartPrice.php19│   │       └── ApplyCouponToCart.php20│   └── Infrastructure/                 # Outer ring – UI and infra21│       ├── Persistence/22│       │   └── DoctrineCartRepository.php23│       └── Http/24│           └── CartPriceController.php25└── SharedKernel/26    └── Domain/27        └── Money.php

Symfony autowiring works for Onion the same way as for Hexagonal. The Application Service depends on the Domain Service and the ports, the outer HTTP adapter on the Application Service. No class in Domain/ contains use Doctrine\…; from Symfony, the core imports only the Symfony\Component\Uid component, which generates identifiers. The other use statements in the core point to classes from Domain/, from the shared kernel (SharedKernel/Domain/), and to identifiers of other contexts (App\*\Domain\ValueObject\*Id).

When Onion fits

  • Domains with extensive Domain Services – a pricing engine, risk scoring, tax calculation, where a lot of logic works with several aggregates at once.
  • Teams that like explicit layering – Onion has a clear name for every layer, and static analysis in CI guards the direction of dependencies. In PHP, Deptrac is used for this, typically with exactly the Domain / Application / Infrastructure layers; the procedure is in the Testing DDD chapter.
  • Enterprise applications with 100+ use cases – where splitting Domain Services from Application Services prevents monolithic “God service” classes.

When Onion makes no sense

A domain with a handful of domain services cannot sustain two layers of services; Hexagonal is then enough. The second obstacle is the team's experience. The boundary between a Domain Service and an Application Service is not intuitive, and misplacing a single class drags an infrastructure dependency all the way into the core.

09.05 Clean Architecture (Robert C. Martin 2012)#

Robert C. Martin (“Uncle Bob”) summed up the common traits of Hexagonal, Onion, his own Screaming Architecture, DCI, and BCE (Boundary-Control-Entity by Ivar Jacobson) in a single model. The result was the 2012 blog post Clean Architecture [7]. Five years later, he expanded it into the book Clean Architecture: A Craftsman's Guide to Software Structure and Design (Prentice Hall, 2017). The book adds chapters on component boundaries and package organization to the pattern.

The four rings of Clean Architecture

  1. Entities – domain objects with the deepest invariants. They correspond to DDD aggregates and value objects. They depend on nothing.
  2. Use Cases – application-specific business rules. In a typical implementation, each use case is a class with one public method (execute() or handle()). They depend only on Entities.
  3. Interface Adapters – Controllers (for input), Presenters (for output), Gateways (for outbound). They translate between the format of the use case and the format of the outside world.
  4. Frameworks & Drivers – Symfony, Doctrine, HTTP clients, database drivers. The outer ring, where everything framework-specific lives.

Dependency Rule: source code dependencies point only inward. An outer layer may refer to classes of an inner layer, never the other way around. If an inner layer needs something from an outer one (e.g., to save an order), it uses Dependency Inversion: it defines the interface on its own side, and the outer layer implements it.

The number four is not binding, though. Martin himself writes that the rings are a schematic and an application may need more of them [7]. The second rule concerns what crosses a boundary: simple data structures, never ORM entities or database rows. The Request and Response DTOs in the examples below are exactly that.

What Clean adds over Onion and Hexagonal

Hexagonal and Onion do not name individual use cases separately: Hexagonal talks about “inbound ports,” Onion about “Application Services.” Clean Architecture elevates the use case to a first-class concept. Every use case is one class with one method and its own Request/Response DTO, so the code itself forms the list of the application's capabilities.

In DDD terms: a Use Case from Clean Architecture ≈ a DDD Application Service ≈ a CQRS command handler. With Symfony Messenger as the command bus (see the CQRS chapter), your PlaceOrderHandler plays the role of the Clean Use Case.

Example: a Use Case with Request/Response DTOs

php src/Ordering/UseCase/PlaceOrder/PlaceOrderRequest.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\UseCase\PlaceOrder;6 7/**8 * Request DTO – input into the use case, framework-agnostic.9 * No Symfony Request, no Doctrine entities, no HTTP details.10 */11final readonly class PlaceOrderRequest12{13    /**14     * @param list<array{productId: string, quantity: int, unitPriceInCents: int}> $items15     */16    public function __construct(17        public string $customerId,18        public array $items,19        public string $shippingAddress,20    ) {21    }22}
php src/Ordering/UseCase/PlaceOrder/PlaceOrderResponse.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\UseCase\PlaceOrder;6 7/**8 * Response DTO – output from the use case. No view, no JSON.9 * The adapter (controller, CLI command) formats the output itself.10 */11final readonly class PlaceOrderResponse12{13    public function __construct(14        public string $orderId,15        public string $status,16        public int $totalAmount,17    ) {18    }19}
php src/Ordering/UseCase/PlaceOrder/PlaceOrderUseCase.php
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\UseCase\PlaceOrder;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\Port\CustomerRepository;9use App\Ordering\Domain\Port\EventPublisher;10use App\Ordering\Domain\Port\OrderRepository;11use App\Ordering\Domain\ValueObject\CustomerId;12use App\Ordering\Domain\ValueObject\OrderId;13use App\Ordering\Domain\ValueObject\ProductId;14use App\SharedKernel\Domain\Currency;15use App\SharedKernel\Domain\Money;16 17final class PlaceOrderUseCase18{19    public function __construct(20        private readonly OrderRepository $orders,21        private readonly CustomerRepository $customers,22        private readonly EventPublisher $events,23    ) {24    }25 26    public function execute(PlaceOrderRequest $request): PlaceOrderResponse27    {28        // A nonexistent customer ends with CustomerNotFoundException from get().29        $customer = $this->customers->get(CustomerId::fromString($request->customerId));30 31        // The canonical Order::place() takes only the identity and the owner; items32        // are added through a method that checks the invariant for each of them.33        $order = Order::place(34            OrderId::generate(),35            $customer->id, // a reference to another aggregate goes through its ID36        );37 38        foreach ($request->items as $item) {39            $order->addItem(40                ProductId::fromString($item['productId']),41                $item['quantity'],42                new Money($item['unitPriceInCents'], Currency::CZK),43            );44        }45 46        $this->orders->save($order);47 48        // Synchronous publishing is enough for development. In production, an49        // Outbox belongs here, otherwise the event is lost on a crash between the write and publishing.50        foreach ($order->releaseEvents() as $event) {51            $this->events->publish($event);52        }53 54        return new PlaceOrderResponse(55            orderId: $order->id->value,56            status: $order->status->value,57            totalAmount: $order->totalAmount()->amountInCents,58        );59    }60}

PlaceOrderUseCase is the single entry point of this application capability. The HTTP controller, the CLI command, the Messenger handler, the GraphQL resolver, and the test all use the same contract: PlaceOrderRequest in, PlaceOrderResponse out.

Adapter: a Symfony HTTP controller as an Interface Adapter

The controller below is a variant of the one from the hexagonal section, not a second file. It has the same namespace, the same class name, and the same /api/orders route, so only one of them can exist in a project.

php src/Ordering/Infrastructure/Http/PlaceOrderController.php (Clean Architecture variant)
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Http;6 7use App\Ordering\UseCase\PlaceOrder\PlaceOrderRequest;8use App\Ordering\UseCase\PlaceOrder\PlaceOrderUseCase;9use Symfony\Component\HttpFoundation\JsonResponse;10use Symfony\Component\HttpFoundation\Request;11use Symfony\Component\Routing\Attribute\Route;12 13final class PlaceOrderController14{15    public function __construct(16        private readonly PlaceOrderUseCase $useCase,17    ) {18    }19 20    #[Route('/api/orders', methods: ['POST'])]21    public function __invoke(Request $request): JsonResponse22    {23        $payload = json_decode($request->getContent(), true, flags: JSON_THROW_ON_ERROR);24 25        $useCaseRequest = new PlaceOrderRequest(26            customerId: $payload['customerId'],27            items: $payload['items'],28            shippingAddress: $payload['shippingAddress'],29        );30 31        $response = $this->useCase->execute($useCaseRequest);32 33        return new JsonResponse([34            'orderId' => $response->orderId,35            'status' => $response->status,36            'totalAmount' => $response->totalAmount,37        ], 201);38    }39}

The controller does exactly three things: it decodes the HTTP input into a PlaceOrderRequest, calls the use case, and formats the output back into JSON. No domain logic, no decision-making. The same use case serves a CLI command of a few lines and a Messenger handler, and a PHPUnit test can call it directly without the framework.

When Clean fits

  • Applications with an explicit list of use cases – where every capability has its own name and contract (e.g., ERP systems, financial applications).
  • Several input channels. HTTP API, CLI, Messenger, and GraphQL share the same use cases.
  • A more experienced team – where the extra layering and the DTO ping-pong do not slow development down.
  • Applications where an audit of “what the application can do” matters – the Use Case classes are that list.

When Clean makes no sense

In an application with thirty endpoints, the DTO ping-pong (Request → Domain → Response) does not pay off. Clean also relies on dependency inversion even more than Hexagonal, so a team without practice in Dependency Injection gets lost in it. Over a thin domain, the use cases end up as nothing more than ritual.

09.06 Vertical Slice Architecture (and horizontal vs. vertical splitting)#

Layer-based architectures have a hidden cost: an ordinary use case spreads across 5–7 files (controller, service, domain service, repository interface, repository implementation, DTO, mapper), and changing a single function touches every one of them. Vertical Slice Architecture, which Jimmy Bogard described in 2018 [8], is a response to that.

Vertical Slice Architecture organizes code by feature, not by layer. Each feature gets its own directory, where everything it needs lives: the command/query, the handler, the validator, the read model, the controller. A slice is a vertical “column” through all the technical layers of the application.

Horizontal splitting – the traditional layered approach

Traditional layered DDD splits a project by technical layers. Each layer has its own directory, and files of a similar type lie together. A typical src/:

bash src/ (traditional DDD structure)
1src/2├── Presentation/                # Presentation layer3│   └── Controller/UserController.php4├── Application/                 # Application layer5│   ├── Service/UserService.php6│   └── DTO/UserDTO.php7├── Domain/                      # Domain layer8│   ├── Model/User.php9│   ├── Repository/UserRepository.php10│   └── Service/DomainUserService.php11└── Infrastructure/              # Infrastructure layer12    ├── Repository/DoctrineUserRepository.php13    └── Persistence/Doctrine/Mapping/User.orm.xml

The layers lie horizontally on top of each other; each one provides services to the one above it. The domain building blocks (entities, value objects, aggregates, domain services) are the same as in any other architectural style.

Vertical splitting – Vertical Slice

A vertical slice reverses the split. The unit is not a layer but a feature. Each function (user registration, placing an order, generating an invoice) has its own directory with everything its implementation needs. The shared domain model stays in {BC}/Domain/; the application and presentation logic and part of the infrastructure are split per feature.

bash src/ (Vertical Slice structure)
1src/2├── UserManagement/             # Bounded Context3│   ├── Domain/                 # Shared domain model of the BC4│   │   ├── Model/User.php5│   │   ├── ValueObject/{UserId, Email}.php6│   │   ├── Event/UserRegistered.php7│   │   └── Repository/UserRepository.php8│   ├── Infrastructure/         # Shared infrastructure of the BC9│   │   └── Repository/DoctrineUserRepository.php10│   ├── Registration/           # Feature: Registration11│   │   ├── Command/{RegisterUser, RegisterUserHandler}.php12│   │   └── Controller/RegistrationController.php13│   └── Profile/                # Feature: Profile14│       ├── Query/{GetUserProfile, GetUserProfileHandler}.php15│       ├── Controller/ProfileController.php16│       └── ViewModel/UserProfileViewModel.php17└── SharedKernel/Domain/Exception/DomainException.php

Coupling between features goes down, and cohesion inside each of them goes up [8]. Bounded Contexts and the shared domain model remain in place.

In his article, Bogard goes further than this structure shows. He objects to the mandatory chain “the controller must call a service, which must use a repository,” and argues that most abstractions fall away inside a slice. In his view, the domain logic pattern is chosen per slice: a trivial slice can be a Transaction Script, a complex one a rich model [8].

This book's convention is deliberately softer. The domain model stays shared within the Bounded Context, and slices cut only the application, presentation, and part of the infrastructure layer. The reason is invariants. An aggregate that each slice models in its own way stops being the single place where the domain rules hold.

What Vertical Slice changes

  • Directory structure – instead of top-level Controller/, Service/, Domain/, Infrastructure/, you have Ordering/PlaceOrder/, Ordering/CancelOrder/, Ordering/GetOrderHistory/ next to the shared Ordering/Domain/.
  • Dependencies between features drop to a minimum. Each feature is almost self-contained; only aggregates, value objects, and the buses (event bus, command bus) are shared.
  • The diff of one feature usually sits in one directory, so the reviewer sees the whole use case in one place during code review. It reaches outside the slice only when it changes the shared domain model.
  • An acceptance test covers the whole slice at once (HTTP request → response) without mocking individual layers.

Comparing horizontal and vertical splitting

Aspect Horizontal (layered) Vertical slice
Code organization By technical layers By functions (features)
Coupling Strong between layers Strong within a feature, weak between features
Changing one use case Edits in 5–7 files across layers Edits in the slice directory, and in the shared Domain/ when a rule changes
Testability Requires more mocks (layers among themselves) Fewer mocks, dependencies are local
Scaling to microservices Requires reorganizing all layers A feature can be moved as a whole
Understanding at the start Easier (more traditional) Requires understanding the slice as a unit
Fit for CQRS CQRS requires extra work Supports CQRS naturally [9]

When to choose which approach

The horizontal (layered) approach pays off for a team with long experience in layered architecture and no plans for CQRS. It suits an application with 10–30 endpoints and low domain complexity. It also fits where the domain model carries invariants shared by many functions and must enforce them uniformly. And it serves a team that prefers an explicit separation of technical layers over organization by function.

A vertical slice pays off when:

  • The application has 50+ functions with independent use cases.
  • The team plans CQRS or has already introduced it (Symfony Messenger as the command/query bus).
  • The application will later be split into microservices, and a feature can be extracted as a whole.
  • You prefer fast iteration with minimal coordination between layers.

A third axis of splitting: the module

Layers and slices are not the only units of division. Martin Fowler writes that once one of the layers grows large, the top level should be split into domain-oriented modules, with layering only inside them [10]. In his view, then, layering is not the right top-level decomposition. In the same text, he warns against organizing teams by layer.

A modular monolith carries the idea through to the deployment level. Kamil Grzybek describes a module by three properties [11]. It is independent and interchangeable. It covers a complete business capability, so modules are vertical slices, not technical layers. And it has a defined interface: everything it shares with the outside becomes its public API. Simon Brown approaches the same thing from the packaging side and, in package by component, recommends relying on the compiler rather than on the team's discipline.

PHP offers no such support, so the boundaries of a module are guarded by static analysis and code review. In practice, this means one directory per module, a set of command and query messages as the public API, and a ban on imports into the internals of another module. Details in the DDD and Microservices chapter.

Vertical Slice and Hexagonal are orthogonal

Hexagonal/Onion/Clean describe how to structure the dependencies inside one feature. Vertical Slice determines how to organize features relative to each other. The two approaches can be combined. Each vertical slice can use a Hexagonal port-adapter structure inside, that is, have its own port, its own adapter, and its own domain service. Or it does not have to. Some slices are so trivial that a single class is enough.

The Hexagonal + Vertical Slice combination is a widespread default choice in Symfony projects. A Bounded Context has a shared domain model (aggregates, value objects, repository interfaces), and the application layer is split into feature slices. Each slice has its own command/handler (or query/handler) and its own HTTP controller. The combination balances testability with a clear structure.

09.07 Practical comparison – what to choose in Symfony 8#

The choice of style depends on the size of the application, the team's experience, the planned horizon of the product, and how much it pays to invest in isolation. The decision matrix below summarizes the typical criteria. Its numbers are the author's rule of thumb, not measured data. They serve to compare the styles with each other, not as a threshold on which a decision could rest by itself.

FIG. 09.7-A Layered vs. Hexagonal vs. Onion vs. Clean – layers and dependency direction
FIG. 09.7-B Four architectural styles applied to DDD
Factor Layered Hexagonal Onion Clean Vertical Slice
Learning curve low medium medium high low
Suitability for juniors ✓✓✓ ✓ ✓ ✗ ✓✓
Domain isolation in tests low high high high medium
Coupling to Doctrine tight (attributes on the entity) loose (through an adapter) loose loose depends on the slice
Several input channels demanding (duplication) natural natural natural natural
Boilerplate (DTOs, mappers) low medium medium high low
Recommended project size < 50 endpoints 50–500 100+ enterprise (200+) 50–500
Fit with CQRS requires changes high (port = command bus) medium high (use case = handler) very high
Changing one feature 5–7 files 4–6 files 5–7 files 6–8 files 1 directory (+ Domain/ when a rule changes)

Recommended default for Symfony 8

For a mid-sized project, the default choice is:

Hexagonal + Vertical Slice with CQRS through Symfony Messenger.

Concretely: the Bounded Context has its own directory (src/Ordering/). Inside Domain/ lie the aggregates, value objects, and repository interfaces (ports); Infrastructure/ contains the Doctrine adapters. Each feature has its own slice (PlaceOrder/, CancelOrder/) with a command/query, a handler (= Clean Use Case), and an HTTP controller. This combination offers:

  • Domain tests without a database – the aggregates are plain PHP, only the ports are mocked.
  • Straightforward code review – the diff of one feature is usually in one directory.
  • CLI/HTTP/Messenger parity – the Symfony Messenger bus dispatches the same command from any adapter.
  • Idiomatic Symfony – Messenger is a first-class component, so you do not have to write your own bus.

This is not a universal truth. An internal administrative application with 20 endpoints is served well enough by the plain Layered structure from the Symfony skeleton, even with a ten-year horizon. The team will most likely iterate faster with it. For an enterprise CRM with 500+ use cases and 15 developers, on the other hand, Clean Architecture with an explicit catalog of use cases pays off.

09.08 Hybrid approach – Hexagonal core, Layered edges#

A real project rarely needs a single style for the whole codebase. More often, it pays to differentiate the investment by subdomain type. The Core Domain gets full Hexagonal with clean aggregates and ports. A Supporting Subdomain makes do with Layered DDD and simplified modeling. A Generic Subdomain is a thin adapter to an external SaaS. This matches Evans's recommendation from the DDD book: modeling effort belongs where it brings a competitive advantage, not everywhere equally.

The classification of subdomains (Core / Supporting / Generic) is covered in detail in the Subdomains: Core, Supporting, Generic chapter.

Example: an online store with differentiated architecture

The classification of the contexts follows the online store from the Mapping subdomains to Bounded Contexts section of the Subdomains chapter. Its competitive advantage lies in pricing and promotions, which is why Pricing gets full Hexagonal. Order management is a Supporting Subdomain there.

bash src/ (hybrid layout of the online store)
1src/2├── Pricing/                            # CORE DOMAIN – full Hexagonal3│   ├── Domain/4│   │   ├── Model/                      # Rich model of prices and discounts5│   │   │   ├── Cart.php6│   │   │   └── DiscountPolicy.php7│   │   ├── ValueObject/8│   │   │   └── CartId.php9│   │   ├── Event/10│   │   │   └── CouponApplied.php11│   │   ├── Service/12│   │   │   └── PriceCalculator.php     # Domain Service13│   │   └── Port/                       # Ports (interfaces)14│   │       ├── CartRepository.php15│   │       └── EventPublisher.php16│   ├── Application/17│   │   └── UseCase/18│   │       ├── ApplyCouponToCart/19│   │       │   ├── ApplyCouponToCart.php        # Command20│   │       │   └── ApplyCouponToCartHandler.php21│   │       └── CalculateCartPrice/22│   │           ├── CalculateCartPrice.php       # Query23│   │           └── CalculateCartPriceHandler.php24│   └── Infrastructure/25│       ├── Persistence/26│       │   ├── DoctrineCartRepository.php27│       │   └── CartOrmEntity.php       # Persistence-friendly mapping28│       └── Http/29│           └── CartPriceController.php30│31├── Ordering/                           # SUPPORTING – Layered DDD32│   ├── Controller/                     # Symfony skeleton structure33│   │   └── OrderController.php34│   ├── Service/35│   │   └── OrderService.php36│   ├── Entity/                         # Doctrine entity directly37│   │   └── Order.php38│   └── Repository/39│       └── OrderRepository.php40│41├── Notifications/                      # GENERIC – thin adapter to SaaS42│   ├── Service/43│   │   └── NotificationService.php44│   └── Provider/45│       ├── SendGridAdapter.php         # Wrapper over an external HTTP API46│       └── TwilioAdapter.php47│48└── SharedKernel/                       # Concepts shared between BCs49    ├── Domain/50    │   ├── Money.php51    │   └── DomainException.php52    └── Bus/53        ├── CommandBus.php              # Interface54        └── EventBus.php

Rules of the hybrid approach

  • The Core Domain gets full Hexagonal, Vertical Slice, and CQRS. This is where the modeling effort, the time for refactoring, and the investment in tests belong.
  • Supporting Subdomains have a Layered structure – controller, service, entity, repository. Such a structure is quick to write and is enough for this type of subdomain.
  • Generic Subdomains are thin adapters. No aggregates, no domain services – only a wrapper around an external library or SaaS API.
  • Styles are not mixed inside one Bounded Context. One BC = one style. Hybrid means “different BCs have different styles,” not “one BC is half Hexagonal and half Layered.”

Cost vs. benefit of the hybrid approach

The cost: the team must know several styles and when to use which. A hybrid therefore needs at least one senior who guards the architecture. Conventions necessarily differ between BCs, and that can confuse readers of the code.

The benefit: the highest ROI on modeling effort. In the Core Domain (where the competitive advantage is decided), you have a clean model and fast tests. In the Generic part (where vendor lock-in is not a problem, because you do not switch SaaS providers every month anyway), you do not invest in isolation that would never pay back.

09.09 Anti-patterns across styles#

Most problems stem not from the choice of style but from its implementation. The following six anti-patterns recur most often in Symfony projects.

Anti-pattern 1: The Hexagonal cult

The team reads Cockburn's article, and every CRUD endpoint gets a port + adapter. GET /api/products/{id} has a port FindProductById, an adapter FindProductByIdHttpAdapter, a repository port ProductRepository, an adapter DoctrineProductRepository, a mapper ProductMapper, and a use case FindProductByIdUseCase. For the most trivial operation, you have six files instead of two.

Remedy: Apply Hexagonal only where there is domain logic. For pure CRUD endpoints (no invariants, no state transitions, no domain rule), a direct Doctrine query in the controller is enough. An architectural style is used when it adds value; it is not an obligation.

Anti-pattern 2: Domain leakage through Doctrine attributes

The classic Layered problem carried over into Hexagonal. The team has Domain/Port/OrderRepository, but the Domain/Model/Order.php class has #[ORM\Entity], #[ORM\Column], and #[ORM\OneToMany]. The domain still depends on the Doctrine library, and the goal of isolation falls apart.

Remedy (for Hexagonal/Onion): Introduce a separate persistence class (OrderOrmEntity) and a mapper, that is, the Persisted Object Pattern. The cost is a duplicate class and explicit mapping, the gain a clean domain. If the project does not really need the Hexagonal boundary, attributes directly on the aggregate are a pragmatic compromise (see the mapping decision).

Anti-pattern 3: Anemic Hexagonal / Anemic Clean

A structurally perfect Hexagonal over an anemic domain full of getters, setters, and logic pushed off into handlers. The detailed description is in the Anti-pattern: Anemic Hexagonal callout in section 09.03; the same applies to Clean.

Remedy: Before introducing an architectural style, check whether your domain model has real behavior. If it does not, solve the modeling first. Hexagonal over an anemic model brings no isolation; it only complicates code review.

Anti-pattern 4: A port per technology

The port is called RedisOrderCache, SendGridMailer, or RabbitMqPublisher. The interface copies the name of the library it wraps, and often the shape of its API too. Cockburn calls this the main mistake he sees with his pattern in practice [4]. One technology per port cancels the whole point of a port, which is replacing the technology without changing the core. The opposite extreme is described in the Anti-pattern: Anemic Hexagonal callout. There, only the repository is a port, and the domain's other outgoing dependencies have no interface at all.

Remedy: Name the port after the conversation the domain conducts, not after the technology on the other end: OrderCache, Mailer, EventPublisher. Each of them can have several adapters underneath, including an in-memory variant for tests. The remaining outgoing dependencies (PaymentGateway, EmailSender) get interfaces too, not only the repository.

Anti-pattern 5: Premature dependency inversion

The team reads up on the “Dependency Inversion Principle” and starts inverting dependencies even where it makes no sense. Interfaces with a single implementation appear that are never mocked. Reading the code gets worse (“I have to jump to the interface and then find the implementation”), without any gain in testability.

Remedy: Dependency inversion is worth it only where at least one of two reasons exists: (1) you want to mock that dependency in tests, (2) you plan several implementations (Doctrine + InMemory, SendGrid + Twilio). When neither holds, the interface is unnecessary.

Anti-pattern 6: Architecture astronaut

The team invests months in a “perfect architecture,” an eight-layer Clean with explicit BCE roles, formal use case catalogs, presenter classes, and gateway hierarchies. The end user is still waiting for the first feature. The architecture has become a goal in itself.

Remedy: Architecture has to return the investment. Every layer, pattern, and abstraction must bring the project a concrete gain. If you cannot explain in five minutes what real problem a given abstraction solves, it probably solves none and should be removed.

More anti-patterns (Anemic Domain Model, God Service, Smart UI, Leaky Abstractions) are covered in detail in the separate Anti-Patterns and Common Mistakes chapter.

09.10 Symfony 8 specifics of all styles#

Whichever style you choose, in Symfony 8 you work with the same tools: the Service Container, Messenger, Doctrine, Form, and Security. Only the conventions of their use differ.

Bundle vs. namespace organization

Symfony used to rely on bundles as the unit of modularity. The official Best Practices today advise the opposite: do not create bundles for your own application logic, and structure src/ directly through namespaces under App\. A bundle is suitable only for reusable libraries published as Composer packages, not for application modules. The rule applies to all architectural styles: for application code, bundles offer nothing that namespaces and autowiring cannot handle.

Per-context configuration in Symfony 8

If you have several Bounded Contexts (Ordering, Billing, Customer, …), each can have its own YAML configuration in config/packages/contexts/. This is useful especially in the hybrid approach, where different BCs have different levels of isolation. Example: only the Core Domain BC has explicit port bindings, the other BCs rely on autowiring.

yaml config/services.yaml (excerpt: imports and exclusions)
1# config/services.yaml2imports:3    - { resource: 'packages/contexts/ordering.yaml' }4    - { resource: 'packages/contexts/billing.yaml' }5    - { resource: 'packages/contexts/customer.yaml' }6 7services:8    _defaults:9        autowire: true10        autoconfigure: true11 12    App\:13        resource: '../src/'14        exclude:15            - '../src/Kernel.php'16            - '../src/**/Domain/Model/'        # Domain models are not services17            - '../src/**/Domain/Event/'        # Neither are events18            - '../src/**/Application/Dto/'     # Nor DTOs

Domain models are excluded from auto-registration in the Service Container. Aggregates, value objects, and domain events are not services; they are data. If they stayed in the container, nothing would break: Symfony removes unused private services when compiling the container, and nobody injects anything into an entity. The exclusion is hygiene. The container is smaller, the configuration more readable, and nobody autowires an aggregate as a dependency by mistake.

The exclusion has one side effect. An excluded directory also drops out of the automatic aliasing of interfaces described above. A port that lies in such a directory then needs an alias written by hand.

Symfony Messenger as the command bus

For all styles except Layered, Symfony Messenger is a suitable tool for the command bus and the event bus. In Layered, the application service is typically called directly from the controller, so it needs no bus. In Hexagonal and Clean Architecture, a use case is usually dispatched as a command, and the handler is either a driving adapter or the use case itself. The configuration of the individual buses:

yaml config/packages/messenger.yaml (excerpt – full configuration in the CQRS chapter)
1# config/packages/messenger.yaml2framework:3    messenger:4        # With more than one bus, default_bus is mandatory, otherwise the container5        # rejects the whole configuration.6        default_bus: command.bus7 8        buses:9            command.bus:10                middleware:11                    # Requires symfony/validator, otherwise the container fails12                    # with “The Validation middleware is only available…”.13                    - validation14                    - doctrine_transaction15            query.bus:16                middleware:17                    - validation18            event.bus:19                default_middleware:20                    enabled: true21                    allow_no_handlers: true   # Events may have 0+ consumers22 23        transports:24            async_events: '%env(MESSENGER_TRANSPORT_DSN)%'25 26        routing:27            # Domain events stay synchronous; the integration form goes out28            # (see the Outbox Pattern chapter).29            App\Ordering\Application\IntegrationEvent\OrderPlacedIntegrationEvent: async_events

Apart from validation, query.bus makes do with the default behavior. Thanks to the default allow_no_handlers: false, a query without a handler gives itself away right at dispatch. The second switch, allow_no_senders, must stay at its default value true. With false, every message without a transport throws NoSenderForMessageException, which means every synchronous query.

Three buses (command, query, event) are usual in a DDD application with CQRS. The Messenger configuration for DDD is covered in detail in the CQRS chapter and in the Implementation in Symfony 8 chapter.

09.11 Summary#

  • An architectural style ≠ DDD. DDD is a modeling technique; an architectural style is a decision about code organization. They can be combined freely – DDD works in Layered, Hexagonal, Onion, Clean, and Vertical Slice.
  • The four layer-based styles rest on the same idea, isolating the domain, but differ in vocabulary and granularity. Hexagonal talks about ports and adapters, Onion about concentric layers, Clean about use cases as a first-class concept. In practice, they are often combined into one hybrid style.
  • Vertical Slice is orthogonal to the layer-based styles. It describes how to organize features relative to each other, not how to structure the dependencies inside a feature. Hexagonal + Vertical Slice + CQRS is a widespread default choice in Symfony 8 projects.
  • The hybrid approach (different styles for different subdomains) is pragmatic, and the DDD literature recommends it. Modeling effort belongs in the Core Domain; Supporting and Generic make do with a simpler structure. Every layer of the architecture must give back to the project what it costs.

Frequently asked questions

Hexagonal vs. Onion – what is the practical difference?

In a typical Symfony implementation, they are almost indistinguishable: both have interfaces in the domain and implementations in the infrastructure, and dependencies point inward. Three subtle differences: Hexagonal explicitly separates driving (inbound) and driven (outbound) ports; Onion sets up Domain Services and Application Services as two separate layers; Onion is a “static” model of dependencies, Hexagonal a “dynamic” model of data flow. If your project uses the Hexagonal vocabulary (port, adapter) but has both a Domain Service and an Application Service inside, you are building a hybrid. That is fine. Details in the Onion Architecture (Palermo 2008) section.

Can I use Hexagonal without DDD?

Yes, technically it works. Hexagonal addresses how to structure dependencies, while DDD describes how to model the domain. They are orthogonal dimensions. You can have Hexagonal over an anemic CRUD model and use no DDD principles at all. The practical gain is limited, though. Without a rich domain model inside, Hexagonal is only layered ritual that makes code review harder and slows development down. The “Anemic Hexagonal” anti-pattern is common in real projects. Details in the Anti-pattern 3: Anemic Hexagonal / Anemic Clean section.

How do I migrate from Layered to Hexagonal in an existing Symfony project?

With the Strangler Fig Pattern: instead of a big rewrite, proceed in parts. Pick one Bounded Context (ideally the Core Domain) and one feature in it. For that feature, introduce a port (an interface in Domain/Port/) and an adapter (the implementation in Infrastructure/), and split the original Doctrine entity into a clean domain class + a persistence OrmEntity + a mapper. Test. Iterate on the next feature. Once the whole Core Domain is done, a second BC can stay in Layered (the hybrid approach). Migrating everything at once carries a high risk of regressions. The Strangler Fig Pattern is covered in detail in the Migrating from CRUD to DDD chapter.

What exactly is a “port,” and how does it differ from an ordinary PHP interface?

A port is an interface with an explicit architectural role: it defines the boundary between the domain and the outside world. Technically, it is an ordinary PHP interface, but by convention it lives in the Domain/Port/ directory, has no framework dependencies, and has a meaningful name from the domain language (OrderRepository, not OrderRepositoryInterface). Cockburn distinguishes driving ports (the outside world calls the domain) and driven ports (the domain calls the outside world). In Symfony, a port is connected to its implementation by an alias, but for an interface with a single discovered implementation, the alias is created automatically. You write it by hand (in services.yaml or with the #[AsAlias] attribute) only when there is more than one implementation or when the directory is excluded from resource. Details in the Hexagonal Architecture (Ports & Adapters, Cockburn 2005) section.

Does Clean Architecture pay off in a small Symfony application?

Most likely not. Clean Architecture requires DTO ping-pong: Request DTO → Use Case → Response DTO → the adapter translates back. That is noticeable overhead, three to four extra classes for every function. In a small application with 20–30 endpoints, it is a pure loss. It pays off only in applications with an explicit list of use cases (200+ capabilities). There, being able to show “what the application can do” matters, and there tend to be several input channels (HTTP, CLI, Messenger, GraphQL). For a small Symfony application, Layered or Hexagonal with less ritual is enough. Details in the Practical comparison – what to choose in Symfony 8 section.

How does Vertical Slice fit in with Hexagonal/Onion/Clean?

Vertical Slice is orthogonal to the layer-based styles. Hexagonal/Onion/Clean describe how to structure the dependencies inside one feature; Vertical Slice describes how to organize features relative to each other. These two dimensions can be combined. Each vertical slice can use a Hexagonal port-adapter structure inside, or it does not have to. In Symfony projects, the combination Hexagonal + Vertical Slice + CQRS through Symfony Messenger is widespread. The Bounded Context has a shared domain model, but the application layer is split into feature slices. Details in the Vertical Slice Architecture (and horizontal vs. vertical splitting) section.

09.12 Further reading and citations#

  1. Eric Evans – Domain-Driven Design: Tackling Complexity in the Heart of Software (2003). The original definition of DDD and the recommendation of a layered architecture.
  2. Martin Fowler – Patterns of Enterprise Application Architecture (2002). Service Layer, Domain Model, Data Mapper, and other fundamental patterns.
  3. Alistair Cockburn – Hexagonal Architecture (Ports and Adapters) (2005). The original article on Hexagonal architecture.
  4. Juan Manuel Garrido de Paz – Interview with Alistair Cockburn (2020). Cockburn clarifies the granularity of ports and the most common mistakes in interpreting the pattern.
  5. Jeffrey Palermo – The Onion Architecture: Part 1 (2008). The first of four blog posts introducing the Onion model.
  6. Jeffrey Palermo – Onion Architecture: Part 4 – After Four Years (2013). The four tenets of the pattern and its distance from DDD, CQRS, and IoC containers.
  7. Robert C. Martin – The Clean Architecture (2012). The original article on Clean Architecture, which generalizes Hexagonal and Onion.
  8. Jimmy Bogard – Vertical Slice Architecture (2018). A feature-first approach to organizing code.
  9. Microsoft – Apply simplified CQRS and DDD patterns in a microservice (.NET microservices architecture guide). How a feature-oriented structure naturally supports CQRS.
  10. Martin Fowler – PresentationDomainDataLayering (2015). The argument for modules at the top level and layers only inside them.
  11. Kamil Grzybek – Modular Monolith: A Primer (2019). The definition of a module and its public API in a modular monolith.
  12. Vaughn Vernon – Implementing Domain-Driven Design (2013). A practical guide to DDD with examples of architectural styles.
  13. Herberto Graça – DDD, Hexagonal, Onion, Clean, CQRS, … How I put it all together (2017). A hybrid view of combining the styles.
  14. Martin Fowler – Anemic Domain Model (2003). The classic article describing the anemic model anti-pattern.
  15. Cockburn, A. & Garrido de Paz, J. M. (2024). Hexagonal Architecture Explained: How the Ports & Adapters Architecture Simplifies Your Life, and How to Implement It. Humans & Technology Press. ISBN 978-1-7375197-8-2. The book treatment of the pattern by its author.
  16. Martin, R. C. (2017). Clean Architecture: A Craftsman's Guide to Software Structure and Design. Prentice Hall. The book-length expansion of the 2012 article.