Hexagonal architecture (ports and adapters): what it is and when to use it
What changes in your code with hexagonal architecture, what ports and adapters look like in practice, and when the pattern is worth the complexity.
You open OrderService to swap the database for another provider and discover that the business rule calls the ORM directly, builds SQL in the middle of a discount calculation, and fires an email before saving. Changing databases just became a weeks-long project with regression risk everywhere. And that isn't even the worst part: to test the discount calculation you need a running database, because the rule and the SQL live in the same method.
Hexagonal architecture (or ports and adapters) is the pattern that separates the application core, where business rules live, from everything that is technology: HTTP, database, queue, email. The core talks to the world only through interfaces (the ports), and each technology plugs in as an adapter that implements or calls those interfaces. This post shows it with a complete PHP example that runs and has a test with no database, and it is honest about when the pattern isn't worth the cost.
Where hexagonal architecture comes from
The pattern was described by Alistair Cockburn in 2005, in the article Hexagonal Architecture. The intent, in his words, is to allow an application to equally be driven by users, programs, automated tests or batch scripts, and to be developed and tested in isolation from the devices and databases it will use at run time.
Note that the original motivation is testability and independence from whoever calls the application, not "swapping databases". The problem Cockburn was attacking was business logic leaking into the user interface, and the interface (screen, database, queue) leaking into the logic.
The hexagon has nothing special to do with the number six. Cockburn himself says the shape was chosen to leave room in the drawing for several ports, and that in practice there are usually two to four. The point is to escape the classic "UI on top, database at the bottom" picture: input goes on the left, output on the right, and the core sits in the middle.
PRIMARY ADAPTERS APPLICATION CORE SECONDARY ADAPTERS
(drive the application) (driven by the application)
+---------------------------------+
HTTP controller ------> | inbound port: PlaceOrder |
CLI command ------> | |
Automated test ------> | PlaceOrderService (application)|
| Order (domain) |
| |
| outbound ports: |
| OrderRepository -------------+---> PdoOrderRepository (SQL)
| | InMemoryOrderRepository (tests)
| PaymentGateway -------------+---> real payment gateway
+---------------------------------+ FakePaymentGateway (tests)
Rule: source-code dependencies point inward. The core imports no adapter.
Ports and adapters: who is who
The most common confusion is thinking every port is "a repository interface". There are two kinds, and direction matters:
- Primary port (driving, inbound): what the outside world can ask the application to do. It is a use case interface, such as
PlaceOrder. It is called by primary adapters: an HTTP controller, a queue consumer, a CLI command, a test. - Secondary port (driven, outbound): what the application needs from the outside world. Persistence, payment gateway, sending email. The application declares the interface; secondary adapters implement it.
Cockburn calls the two sides primary actors (which drive the application) and secondary actors (which the application drives), and says the adapters can also be called driving and driven.
A detail many tutorials get wrong: ports belong to the application, the whole hexagon (use cases plus domain), not just the domain. A primary port describes a use case, so it lives in the application layer. A secondary port usually lives there too, because the thing that needs "save order" and "charge card" is the use case. If your domain model is rich, a repository can be declared next to its aggregate; what must not happen is the interface living next to the adapter.
Practical PHP example: folder structure
The example is an order use case: it takes items, charges the total to a card, and saves. The structure:
src/
Domain/
Order/Order.php, OrderId.php pure business rules
Application/
Port/In/PlaceOrder.php primary port (interface)
Port/In/PlaceOrderCommand.php use case input data
Port/Out/OrderRepository.php secondary port
Port/Out/PaymentGateway.php secondary port
PlaceOrderService.php implements the primary port
Adapter/
In/Http/PlaceOrderController.php primary adapter
Out/Persistence/PdoOrderRepository.php secondary adapter
tests/
InMemoryOrderRepository.php, FakePaymentGateway.php, PlaceOrderServiceTest.php
Names vary between teams (Infrastructure/ instead of Adapter/Out, UI/ instead of Adapter/In); what matters is that nothing in Domain/ or Application/ imports anything from Adapter/. Autoloading is plain PSR-4 ("App\\": "src/", "Tests\\": "tests/").
The primary port and the service that implements it
The inbound port is an interface. The application service implements it and depends only on the outbound ports:
<?php
declare(strict_types=1);
namespace App\Application\Port\In;
use App\Domain\Order\OrderId;
// Primary (driving) port: what the outside world can ask the application to do
interface PlaceOrder
{
public function place(PlaceOrderCommand $cmd): OrderId;
}
<?php
declare(strict_types=1);
namespace App\Application;
use App\Application\Port\In\PlaceOrder;
use App\Application\Port\In\PlaceOrderCommand;
use App\Application\Port\Out\OrderRepository;
use App\Application\Port\Out\PaymentGateway;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
// Application service: IMPLEMENTS the primary port and DEPENDS on the secondary ones
final class PlaceOrderService implements PlaceOrder
{
public function __construct(
private readonly OrderRepository $orders,
private readonly PaymentGateway $payments,
) {}
public function place(PlaceOrderCommand $cmd): OrderId
{
$order = Order::place(OrderId::generate(), $cmd->customerId, $cmd->items);
$this->payments->charge($order->totalCents(), $cmd->cardToken);
$this->orders->save($order);
return $order->id;
}
}
The domain is plain PHP, no framework. Order::place() rejects an empty order and totalCents() sums the items. The rule is small here on purpose; in a real system this is where invariants, state machines and tax calculations live. If you are still deciding how much behavior belongs in the domain, the post on DDD for small projects discusses rich versus anemic models.
<?php
declare(strict_types=1);
namespace App\Domain\Order;
final class Order
{
/** @param list<array{sku: string, qty: int, unitCents: int}> $items */
private function __construct(
public readonly OrderId $id,
public readonly string $customerId,
public readonly array $items,
) {}
/** @param list<array{sku: string, qty: int, unitCents: int}> $items */
public static function place(OrderId $id, string $customerId, array $items): self
{
if ($items === []) {
throw new \DomainException('Order has no items');
}
return new self($id, $customerId, $items);
}
public function totalCents(): int
{
return array_sum(array_map(fn (array $i) => $i['qty'] * $i['unitCents'], $this->items));
}
}
OrderId is a one-line value object (public readonly string $value, with generate() using random_bytes) and PlaceOrderCommand is a DTO with customerId, items and cardToken.
The secondary ports and the database adapter
Outbound ports are interfaces in the application layer:
<?php
declare(strict_types=1);
namespace App\Application\Port\Out;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
// Secondary (driven) port: what the application needs from the outside world
interface OrderRepository
{
public function save(Order $order): void;
public function ofId(OrderId $id): ?Order;
}
// In Port/Out/PaymentGateway.php:
// interface PaymentGateway { public function charge(int $amountCents, string $cardToken): void; }
The adapter lives at the edge and is the only piece that knows SQL exists. I used PDO so the example runs with no dependencies; with Doctrine the shape is the same, swapping PDO for Doctrine\ORM\EntityManagerInterface plus a mapper between the domain Order and the ORM entity.
<?php
declare(strict_types=1);
namespace App\Adapter\Out\Persistence;
use App\Application\Port\Out\OrderRepository;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
use PDO;
// Secondary adapter: knows SQL and PDO; the application does not know it
final class PdoOrderRepository implements OrderRepository
{
public function __construct(private readonly PDO $pdo) {}
public function save(Order $order): void
{
$this->pdo->prepare(
'INSERT INTO orders (id, customer_id, items_json) VALUES (:id, :customer, :items)'
)->execute([
'id' => $order->id->value,
'customer' => $order->customerId,
'items' => json_encode($order->items, JSON_THROW_ON_ERROR),
]);
}
public function ofId(OrderId $id): ?Order
{
$stmt = $this->pdo->prepare('SELECT customer_id, items_json FROM orders WHERE id = :id');
$stmt->execute(['id' => $id->value]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row === false) {
return null;
}
$items = json_decode($row['items_json'], true, 512, JSON_THROW_ON_ERROR);
return Order::place($id, $row['customer_id'], $items);
}
}
This is dependency inversion in practice: the high-level module (the use case) and the low-level one (the SQL) depend on the same abstraction, which belongs to the high level. The post on SOLID principles covers the "D" in more depth.
The primary adapter: an HTTP controller
On the inbound side, the controller translates HTTP into a call on the port. It depends on the PlaceOrder interface, not the concrete service, and turns the domain exception into an HTTP status:
<?php
declare(strict_types=1);
namespace App\Adapter\In\Http;
use App\Application\Port\In\PlaceOrder;
use App\Application\Port\In\PlaceOrderCommand;
// Primary adapter: translates HTTP into the inbound port. Knows the port, not the service.
final class PlaceOrderController
{
public function __construct(private readonly PlaceOrder $placeOrder) {}
/** @return array{0: int, 1: array<string, mixed>} [status, JSON body] */
public function __invoke(array $body): array
{
try {
$id = $this->placeOrder->place(new PlaceOrderCommand(
customerId: (string) ($body['customer_id'] ?? ''),
items: $body['items'] ?? [],
cardToken: (string) ($body['card_token'] ?? ''),
));
} catch (\DomainException $e) {
return [422, ['error' => $e->getMessage()]];
}
return [201, ['order_id' => $id->value]];
}
}
I kept the controller framework-free so the example fits in a post; in Laravel or Symfony it would take the Request and return a JsonResponse, but it would still depend only on the port. What wires everything together is the composition root (the DI container, or a bootstrap.php), the only place that knows concrete classes:
$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$controller = new PlaceOrderController(
new PlaceOrderService(new PdoOrderRepository($pdo), $paymentGateway),
);
Running the example with in-memory SQLite on php:8.4-cli, a valid order returns 201 {"order_id":"..."} and writes one row; an order with no items returns 422 {"error":"Order has no items"}. Compared with the controller, service and repository model most projects use, the difference is not in the classes, which are nearly the same, but in the direction of the dependencies: here the service does not import the concrete repository, only the interface it declared itself.
Testing without a database: the in-memory adapter
This is the central promise of the pattern, and the reason I use it. Since the service only knows the ports, the test plugs in-memory adapters in place of the database and the gateway:
<?php
declare(strict_types=1);
namespace Tests;
use App\Application\Port\Out\OrderRepository;
use App\Domain\Order\Order;
use App\Domain\Order\OrderId;
final class InMemoryOrderRepository implements OrderRepository
{
/** @var array<string, Order> */
private array $orders = [];
public function save(Order $order): void
{
$this->orders[$order->id->value] = $order;
}
public function ofId(OrderId $id): ?Order
{
return $this->orders[$id->value] ?? null;
}
public function count(): int
{
return count($this->orders);
}
}
FakePaymentGateway implements PaymentGateway, stores the charged amounts in a public $charged array and throws DomainException when the token is tok_declined. With both in place, the use case test:
<?php
declare(strict_types=1);
namespace Tests;
use App\Application\PlaceOrderService;
use App\Application\Port\In\PlaceOrderCommand;
use PHPUnit\Framework\TestCase;
final class PlaceOrderServiceTest extends TestCase
{
public function test_charges_the_total_and_saves_the_order(): void
{
$orders = new InMemoryOrderRepository();
$payments = new FakePaymentGateway();
$service = new PlaceOrderService($orders, $payments);
$id = $service->place(new PlaceOrderCommand('cust-42', [
['sku' => 'SHIRT', 'qty' => 2, 'unitCents' => 4990],
['sku' => 'SOCKS', 'qty' => 1, 'unitCents' => 1500],
], 'tok_ok'));
self::assertSame([11480], $payments->charged);
self::assertSame('cust-42', $orders->ofId($id)?->customerId);
}
public function test_declined_payment_does_not_save_the_order(): void
{
$orders = new InMemoryOrderRepository();
$service = new PlaceOrderService($orders, new FakePaymentGateway());
try {
$service->place(new PlaceOrderCommand('cust-42', [
['sku' => 'SHIRT', 'qty' => 1, 'unitCents' => 4990],
], 'tok_declined'));
self::fail('Should have thrown DomainException');
} catch (\DomainException) {
self::assertSame(0, $orders->count());
}
}
}
I ran it with PHPUnit 12.5 on php:8.4-cli: 2 tests, 3 assertions, green in 46 ms. The absolute number means little in an example this size; what matters is that none of these tests needs a database, a network or a container, so they don't break because of flaky infrastructure.
Note that these are fakes, simplified implementations that actually work, not mocks with call expectations. The difference matters, and it is explained in mock, stub, fake and spy. PdoOrderRepository still needs tests, but integration tests against a real database; that is the kind of test the post on integration vs unit tests argues for.
Hexagonal vs Clean Architecture vs traditional layers
The three show up together in every discussion, and for good reason: hexagonal and Clean say almost the same thing with different vocabulary.
| Traditional layers | Hexagonal (Cockburn, 2005) | Clean Architecture (Martin, 2012) | |
|---|---|---|---|
| Metaphor | Stack: UI, business, data | Core with ports and adapters | Concentric circles |
| Dependency direction | Top-down, business depends on data access | Inward, adapters depend on the core | Inward (the Dependency Rule) |
| Emphasis | Separating responsibilities | Inbound vs outbound side, swapping adapters | Named layers: entities, use cases, interface adapters, frameworks |
| Database | Bottom of the stack | Just another secondary adapter | A detail in the outermost layer |
| Testing without infrastructure | Hard without mocking data access | Natural: in-memory adapters | Natural: same mechanism |
Robert C. Martin's article The Clean Architecture explicitly lists hexagonal architecture as one of the ideas it unifies. In practice you end up mixing both vocabularies, and that is fine. The post on Clean Architecture: benefits and pitfalls covers the concentric-layers side and where dependency inversion turns into theater.
The cost nobody puts on the slide
Hexagonal isn't free. Each secondary port becomes at least an interface, a real implementation and a fake for tests, and with an ORM a mapper between the domain model and the persistence entity usually comes along. For a product-catalog CRUD that is pure ceremony: four files to run one INSERT.
The real risk is over-engineering. Creating a port for everything, including what will never be swapped or tested in isolation, is the shortest path to a codebase where opening a file means hopping through six indirections to find the line that actually does something.
When it's worth it and when it isn't
It is worth it when you have domain logic that matters (rules, invariants, state machines) and when testability is a priority: financial, tax and ordering systems, anything where a bug is expensive. It is also worth it when the same rule is called from more than one entry point, such as HTTP, a queue and a scheduled job, which is exactly the scenario Cockburn described.
It is not worth it for a thin CRUD, a backend-for-frontend that just relays calls, a script, or an MVP you're not sure will exist in three months. In those cases the domain is so anemic that the port protects nothing.
My heuristic: apply ports and adapters only at the boundary that hurts. If the database never changes but the payment integration has already switched providers twice, put a port on payments and let persistence use the ORM directly. Architecture is deciding where to spend complexity, not applying the whole pattern everywhere.
Frequently asked questions
What is hexagonal architecture in simple terms?
It is a way of organizing code so business rules don't depend on external details like the database, web framework or queue. The application core defines interfaces (ports) and the outside world comes in through adapters that call or implement those interfaces. That lets you test the rules without infrastructure and swap technology without rewriting the logic.
What is the difference between a port and an adapter?
A port is the interface, the contract, and it belongs to the application. An adapter is the concrete implementation that connects a technology to that port: the HTTP controller that calls the inbound port, or the SQL repository that implements the outbound port. One port can have several adapters, such as the SQL repository in production and the in-memory repository in tests.
What is the difference between hexagonal architecture and Clean Architecture?
Both defend the same rule: dependencies point toward the core. Hexagonal, from 2005, organizes the design by direction (inbound and outbound) and by swapping adapters; Clean Architecture, from 2012, organizes it into concentric layers with fixed names and cites hexagonal as one of its sources. Teams commonly use both vocabularies at once.
Can I use hexagonal architecture with Laravel or Symfony?
Yes. The framework stays in the adapters: controllers, Eloquent or Doctrine, queues. The core (domain, ports and application services) is plain PHP, and the framework's DI container acts as the composition root, binding each interface to its concrete adapter. The cost is giving up some shortcuts, such as using Eloquent models directly inside business rules.
Hexagonal architecture is about direction, not hexagons
What the pattern gives you is a rule that is easy to check: the core imports nothing from outside, and each technology comes in through an adapter connected to a port the application declared. The concrete payoff is testing business rules with in-memory adapters and connecting the same rule to HTTP, a queue or a CLI without duplicating code. Start with the primary port and the secondary ports that hurt today, keep the composition root as the only place that knows concrete classes, and don't create an interface for something that will never have a second implementation.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.