Lesson 4 of 15 · Architectural Styles
Hexagonal Architecture (Ports and Adapters)
The problem hexagonal solves
A Laravel application has its business logic spread across controllers, Eloquent models, service classes, jobs, listeners, and console commands. The framework is in the middle of every business operation. Tests for the business require booting Laravel. Switching the mailer means editing controllers. Running the same use case from a queue worker requires duplicating the code.
This is the codebase Hexagonal Architecture was invented to fix. Alistair Cockburn described it in a 2005 article under two names, "Hexagonal Architecture" and "Ports and Adapters". The premise was simple: the application should be independent of the way it's driven, and independent of the systems it drives.
Onion Architecture (Jeffrey Palermo, 2008) and Clean Architecture (Robert C. Martin, 2012) came later. Martin's article lists Hexagonal Architecture and Onion Architecture among its predecessors and says they "are very similar".
The shape
The image Cockburn drew was a hexagon. The hexagon represents the application: business logic, domain rules, use cases. A use case is one thing someone can ask the application to do, like requesting a reservation. Outside the hexagon are the things that talk to the application (HTTP, CLI, queues, schedulers) and the things the application talks to (databases, mailers, payment gateways, search indexes).
Between the application and the outside, two concepts:
Ports. Interfaces that the application defines. They describe what the application needs (a
Mailer, aReservationsrepository) or what the application exposes (a use case). In this lesson's example the exposed port is a command plus its handler, not an interface.Adapters. Concrete implementations of those interfaces. The Eloquent implementation of
Reservations. The Mailgun implementation ofMailer. The HTTP controller that calls a use case. The CLI command that calls the same use case.
Driving and driven sides
The hexagon has two sides:
Driving (or "primary") side. Things that drive the application. They cause the application to do work. HTTP requests, console commands, queue messages, scheduled jobs. Adapters here translate the trigger into a call to a use case.
Driven (or "secondary") side. Things the application drives. They do work the application asks for. Databases, mailers, payment gateways, file storage, third-party APIs. Adapters here implement the ports the core needs.
The directions matter. The driving side calls inward; the driven side is called from inward. Both sides have ports (interfaces) and adapters (implementations), but the ports on the driving side are usually use case definitions, while the ports on the driven side are usually capability needs.

The core sits in the middle. The ports are owned by the core. The adapters wrap the outside. The dependencies point inward: the core knows nothing about the adapters; the adapters know about the core.
A worked example
A reservation system, hexagonally. The files follow the Booking module layout the rest of this course uses, with the use case in its own RequestReservation/ folder, called a slice, and the entity classes in Reservation/.
Hearth/Booking/
├── RequestReservation/ # slice
│ ├── RequestReservationController.php # driving adapter
│ ├── RequestReservationConsoleCommand.php # driving adapter
│ ├── RequestReservationRequest.php
│ ├── RequestReservationCommand.php # driving port
│ └── RequestReservationCommandHandler.php # driving port
├── Reservation/
│ ├── Reservation.php
│ └── Reservations.php # driven port
├── Rooms.php # driven port
├── Room.php
├── Clock.php # driven port
├── Dispatcher.php # driven port
├── Infrastructure/
│ ├── EloquentReservations.php # driven adapter
│ ├── EloquentRooms.php # driven adapter
│ ├── SystemClock.php # driven adapter
│ └── LaravelDispatcher.php # driven adapter
└── BookingServiceProvider.php # binds portsThe application core has a use case. Its input is a command, a plain object that names the use case and carries the data it needs:
<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\RoomId;
final readonly class RequestReservationCommand
{
public function __construct(
public GuestId $guestId,
public RoomId $roomId,
public DateRange $stayDates,
public GuestCount $guestCount,
) {
}
}The handler runs it. It is the previous lesson's RequestReservation application service, renamed RequestReservationCommandHandler and moved into its slice. Reservation, ReservationId, CancellationPolicy, RoomNotAvailable and ReservationPriceFactory are the classes that lesson used. This version also calls Reservation::releaseEvents(), which returns the events the entity recorded and which the previous lesson's trimmed Reservation left out:
<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Hearth\Booking\Clock;
use Hearth\Booking\Dispatcher;
use Hearth\Booking\Reservation\CancellationPolicy;
use Hearth\Booking\Reservation\Reservation;
use Hearth\Booking\Reservation\ReservationId;
use Hearth\Booking\Reservation\Reservations;
use Hearth\Booking\Reservation\RoomNotAvailable;
use Hearth\Booking\ReservationPriceFactory;
use Hearth\Booking\Rooms;
final readonly class RequestReservationCommandHandler
{
public function __construct(
private Reservations $reservations, // driven port
private Rooms $rooms, // driven port
private ReservationPriceFactory $priceFactory,
private CancellationPolicy $cancellationPolicy,
private Clock $clock, // driven port
private Dispatcher $dispatcher, // driven port
) {
}
public function handle(RequestReservationCommand $command): ReservationId
{
$room = $this->rooms->withId($command->roomId);
if ($this->reservations->overlapping($command->roomId, $command->stayDates) !== []) {
throw new RoomNotAvailable($command->roomId, $command->stayDates);
}
$totalPrice = $this->priceFactory->build($room, $command->stayDates, $command->guestCount);
$reservation = Reservation::request(
$command->guestId,
$command->roomId,
$command->stayDates,
$command->guestCount,
$totalPrice,
$this->cancellationPolicy,
$this->clock->now(),
);
$this->reservations->save($reservation);
foreach ($reservation->releaseEvents() as $event) {
$this->dispatcher->dispatch($event);
}
return $reservation->id;
}
}Notice what's not imported: anything from Illuminate\* or a vendor SDK, anything HTTP-shaped. The handler is pure PHP plus its own ports.
The driven ports (interfaces the core needs). Each interface is its own file; they are shown together here:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Reservation;
use Hearth\Booking\DateRange;
use Hearth\Booking\RoomId;
interface Reservations
{
public function withId(ReservationId $id): Reservation;
public function save(Reservation $reservation): void;
/** @return list<Reservation> */
public function overlapping(RoomId $roomId, DateRange $stayDates): array;
}<?php
declare(strict_types=1);
namespace Hearth\Booking;
interface Rooms
{
public function withId(RoomId $id): Room;
}Room is Booking's own view of a room: the id and how many guests it holds. Housekeeping's room, with its cleaning status, is a different class in a different module.
<?php
declare(strict_types=1);
namespace Hearth\Booking;
final readonly class Room
{
public function __construct(
public RoomId $id,
public int $capacity,
) {}
}Clock and Dispatcher are the two ports that aren't about the hotel at all. Booking still owns them, in its own namespace, so that no other module has to be imported to build one:
<?php
declare(strict_types=1);
namespace Hearth\Booking;
use Carbon\CarbonImmutable;
interface Clock
{
public function now(): CarbonImmutable;
}<?php
declare(strict_types=1);
namespace Hearth\Booking;
interface Dispatcher
{
public function dispatch(object $event): void;
}The driven adapters (Eloquent implementation, Laravel dispatcher, etc.). EloquentReservations is the one from the previous lesson, and EloquentRooms has the same shape over a rooms table:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Infrastructure;
use Carbon\CarbonImmutable;
use Hearth\Booking\Clock;
final readonly class SystemClock implements Clock
{
public function now(): CarbonImmutable
{
return CarbonImmutable::now();
}
}<?php
declare(strict_types=1);
namespace Hearth\Booking\Infrastructure;
use Hearth\Booking\Dispatcher;
use Illuminate\Contracts\Events\Dispatcher as IlluminateDispatcher;
final readonly class LaravelDispatcher implements Dispatcher
{
public function __construct(private IlluminateDispatcher $dispatcher)
{
}
public function dispatch(object $event): void
{
$this->dispatcher->dispatch($event);
}
}The driving adapters (HTTP and CLI). Both hand the command to a command bus, which takes a command object and calls the one handler registered for that command type. Laravel ships one, Illuminate\Contracts\Bus\Dispatcher (not Booking's own event Dispatcher port above), and the provider below registers the pairing. The command and its handler are the driving port: the adapters know the command, the core doesn't know who sent it.
<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\RoomId;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(private Dispatcher $bus)
{
}
public function __invoke(RequestReservationRequest $request): JsonResponse
{
$id = $this->bus->dispatchSync(new RequestReservationCommand(
guestId: new GuestId($request->string('guest_id')->toString()),
roomId: new RoomId($request->string('room_id')->toString()),
stayDates: new DateRange(
checkIn: CarbonImmutable::parse($request->string('check_in')->toString()),
checkOut: CarbonImmutable::parse($request->string('check_out')->toString()),
),
guestCount: new GuestCount(
adults: $request->integer('adults'),
children: $request->integer('children'),
),
));
return new JsonResponse(['id' => $id->toString()], 201);
}
}RequestReservationRequest is the Form Request from the previous lesson, moved into the slice folder.
<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\RoomId;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Contracts\Bus\Dispatcher;
#[Signature('reservations:request {guest} {room} {check-in} {check-out} {adults=1} {children=0}')]
#[Description('Request a reservation the same way the booking form does')]
final class RequestReservationConsoleCommand extends Command
{
public function handle(Dispatcher $bus): int
{
$id = $bus->dispatchSync(new RequestReservationCommand(
guestId: new GuestId($this->argument('guest')),
roomId: new RoomId($this->argument('room')),
stayDates: new DateRange(
checkIn: CarbonImmutable::parse($this->argument('check-in')),
checkOut: CarbonImmutable::parse($this->argument('check-out')),
),
guestCount: new GuestCount(
adults: (int) $this->argument('adults'),
children: (int) $this->argument('children'),
),
));
$this->info("Reservation {$id->toString()} requested.");
return Command::SUCCESS;
}
}Both adapters call the same use case, the same way. The use case doesn't know it's being driven by HTTP or CLI.
The container wires the ports to the adapters at boot, and Bus::map pairs the command with its handler, in Hearth/Booking/BookingServiceProvider.php:
<?php
declare(strict_types=1);
namespace Hearth\Booking;
use Hearth\Booking\Infrastructure\EloquentReservations;
use Hearth\Booking\Infrastructure\EloquentRooms;
use Hearth\Booking\Infrastructure\LaravelDispatcher;
use Hearth\Booking\Infrastructure\SystemClock;
use Hearth\Booking\Reservation\CancellationPolicy;
use Hearth\Booking\Reservation\FreeWindowCancellationPolicy;
use Hearth\Booking\Reservation\Reservations;
use Hearth\Booking\RequestReservation\RequestReservationCommand;
use Hearth\Booking\RequestReservation\RequestReservationCommandHandler;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\ServiceProvider;
final class BookingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(Reservations::class, EloquentReservations::class);
$this->app->bind(Rooms::class, EloquentRooms::class);
$this->app->bind(Clock::class, SystemClock::class);
$this->app->bind(Dispatcher::class, LaravelDispatcher::class);
$this->app->bind(CancellationPolicy::class, FreeWindowCancellationPolicy::class);
}
public function boot(): void
{
Bus::map([
RequestReservationCommand::class => RequestReservationCommandHandler::class,
]);
}
}Tests bind fakes over the same ports. Testing Across the Boundary builds those fakes.
The dependency rule
In a Laravel codebase, the dependency rule looks like:
Hearth/Booking/RequestReservation/RequestReservationCommandHandler.phpimports nothing fromIlluminate\*, nothing from third-party SDKs.Hearth/Booking/Reservation/Reservations.php(the port) is a plain PHP interface.Hearth/Booking/Infrastructure/EloquentReservations.php(the adapter) imports Eloquent. That's where the framework lives.Hearth/Booking/RequestReservation/RequestReservationController.phpimportsIlluminate\Http. That's the driving adapter.
What you actually get
Replaceable infrastructure. Switching the mailer from Mailgun to Postmark is a new adapter and a binding change. The core doesn't move.
Fast tests for the core. Unit tests for
RequestReservationCommandHandlerboot zero framework. They construct the handler with fakes, callhandle()with a command, and assert on the recorded events.Multiple drivers, one core. The same use case runs from HTTP, queues, console commands, webhooks, and integration tests, with one definition.
Framework upgrades become localized. Laravel 12 to Laravel 13 is a question of "did our adapters keep working?", not "did the whole codebase keep working?".
When hexagonal earns its place
It earns its place when:
Infrastructure dependencies are expected to change. A migration from one search engine to another, one mailer to another, one payment gateway to another. The port absorbs the change.
The domain has rules that deserve their own space. Pricing logic, scheduling rules, eligibility rules. Things that benefit from being framework-free.
It doesn't earn its place when:
The framework is the product. Some applications are mostly framework integration glue. Hexagonalizing them is fighting the gravity of what they are.
The codebase is in early-stage discovery. You don't know the ports yet. Drawing them prematurely guesses at the wrong shape.
Pitfalls
Hexagonalizing everything. Every concrete class hidden behind an interface. Every constant turned into a port. The codebase fills up with ceremony. Hexagonal applies to the seam between the application and the outside world, not to every internal collaboration.
The leaky core. A handler that imports Illuminate\Database\Connection directly, even though it has a Reservations port available. Subsequent code follows the precedent. Static analysis (Deptrac, PHPArkitect) helps catch this. Without enforcement, the rule erodes.
Ports that mirror the framework. A Mailer interface with a send($view, $data, $callback) signature is just Laravel's mailer in disguise. The port should be domain-shaped. Mailer::send(EmailMessage) is better.
Treating "no Eloquent in the core" as religious. The pragmatic version of this course's codebase keeps Eloquent models in the infrastructure layer. The core uses domain entities mapped from Eloquent. The line is "no Eloquent in the core", not "no Eloquent at all". This differs from Laravel's Active Record default of using the Eloquent model itself as the entity; the course keeps a plain Reservation behind the Reservations port because the port is what this lesson teaches.
Building all the ports up front. A green-field project that starts with twenty ports and zero adapters is doing too much before learning the domain. Discover the ports as the use cases reveal them; don't speculate.
The one thing to remember
Hexagonal Architecture is your application defining the interfaces it needs, and the framework providing implementations of them. The core is independent of how it's driven and what it drives. The dependencies point inward.
Related Links
- Hexagonal ArchitectureAlistair Cockburn's original article defining ports and adapters, the source for this lesson's vocabulary.
- Ready for changes with Hexagonal ArchitectureNetflix's Studio Workflows team describes applying Hexagonal Architecture so the core business logic knows nothing about the transport layer or the data sources.
- Ports & Adapters ArchitectureA worked-through explanation of the pattern with diagrams, a second angle on the same shape Cockburn's article defines.