Skip to content

Lesson 2 of 15 · Architectural Styles

Layered Architecture and the Dependency Rule

Advanced•
lesson•
November 16, 2026•
~11 min read

Same bug, one method

Say a guest reports a bug: they received a confirmation email, but the reservation is not in the system. You open the codebase to find out why.

The ReservationController calls a BookingService. The BookingService builds an Eloquent Reservation model, saves it, calls Mail::to($guest)->send(...) directly, and returns a response array. There's no separate place where "confirming a reservation" is a concept. It's just steps inside one method, spread across a controller and a service class that both know about HTTP, Eloquent, and the mailer.

You find the bug: the mail call happens before the database write, and if the write fails, the guest still gets an email for a reservation that doesn't exist. Fixing the order is a two-line change. But now you're also stuck answering a harder question: where should the code that decides confirmation order actually live, so this doesn't happen again in the next feature?

That's the question this chapter answers with three different structures: Hexagonal Architecture, Clean Architecture and Vertical Slice Architecture. All three are answers to one underlying problem. Before comparing them, you need to know what a layer is, why they exist, and the one rule that makes any of them work.

What a layer actually is

A layer is a group of code that changes for the same reason, and that talks to its neighboring layers through a narrow, deliberate surface instead of reaching in and touching their internals directly.

Two things have to be true for something to count as a layer:

  • A shared reason to change. Everything inside the layer changes together, for the same kind of reason. The code that talks to Stripe changes when Stripe changes their API. The code that decides whether a reservation can be cancelled changes when the cancellation policy changes. Those are different reasons, so they're different layers.

  • A narrow surface to its neighbors. A layer doesn't let other layers reach into its internals. It exposes a small set of entry points (a method, an interface, a constructor) and hides how it does its job behind them. The Reservations repository interface is a narrow surface. Letting every part of the app run raw SQL against the reservations table is not a surface at all.

Without both of those, "layer" just means "directory". A Services/ folder where every class does something different for a different reason, and reaches into whichever other class it needs, is a filing cabinet.

Why layers exist

Layers solve three problems.

The first is rate of change. Business rules change often: pricing rules, cancellation windows, what counts as a valid guest count. Infrastructure changes rarely and on its own schedule: you don't switch database engines because a product manager asked for a new field. When code for both lives in the same class, a change to one drags the other along for no reason. A cancellation policy tweak shouldn't require you to re-test the HTTP layer.

The second is testing strategy. Business rules want fast, isolated tests that don't touch a database. Code that talks to Eloquent wants integration tests against a real database, because the point is checking the SQL does what you think. A method that mixes both concerns forces one slow, brittle test suite to cover jobs that want different tools.

The third is ownership. On a larger team, someone owns the domain rules, someone owns the API surface, someone owns the database. Layers give each person a place to work without their changes colliding in the same file, and a question a reviewer can actually ask: does this diff put infrastructure code inside the domain layer?

The classic three-layer model

The simplest version of this idea splits the application into three layers, stacked so each one can only call the layer directly below it.

Three stacked layers. Presentation at the top: controllers, views, request and response. Application and business logic in the middle: use cases, domain rules, workflows. Infrastructure and data at the bottom: database, external APIs, file system. Arrows point down from each layer to the one below it, with the note that lower layers never call upward.
  • Presentation handles the request and response, nothing else. HTTP controllers, CLI commands, queue job handlers, GraphQL resolvers. It translates between the outside world's shape (an HTTP request, a console argument list) and whatever the layer below needs to do its job. It shouldn't know what a cancellation policy is.

  • Application and business logic is where the actual rules live, in classes called use cases: one class per thing a user can ask the system to do. This is the layer that knows what "confirm a reservation" means: check the room is still available, check the payment authorized, move the reservation to confirmed, fire the event that triggers the email. Nothing here should know it's being called from HTTP versus a queue worker.

  • Infrastructure and data is everything that talks outward: the database, third-party APIs, the filesystem, the mail provider. It implements what the layer above asks for, without deciding when or why to do it.

The hotel app in this course is called Hearth. Its code lives in Hearth/, mapped to the Hearth\ namespace, where Building Maintainable PHP Applications: Foundations and Building Maintainable PHP Applications: Patterns and Principles used Laravel's default App\. The layout below illustrates the layered style, before slices are introduced.

TEXT
Hearth/Booking/ ├── Presentation/Http/Controllers/ # presentation │ └── ConfirmReservationController.php ├── Application/ # application │ ├── ConfirmReservation.php # the use case │ ├── ConfirmReservationCommand.php │ └── Payments.php # Payments module implements ├── Domain/ # domain │ ├── Reservation.php │ ├── Reservations.php # repository interface │ ├── CancellationPolicy.php │ └── FreeWindowCancellationPolicy.php └── Infrastructure/ # infrastructure ├── EloquentReservations.php # implements Reservations └── ReservationRecord.php # Eloquent model

Put the hotel example through it. An HTTP controller (presentation) receives the confirm request and calls a ConfirmReservation use case (application). The use case checks the rules and asks a Reservations repository to persist the change. Here's what that split looks like as code, with the dependency rule respected:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Presentation\Http\Controllers; use Carbon\CarbonImmutable; use Hearth\Booking\Application\ConfirmReservation; use Hearth\Booking\Application\ConfirmReservationCommand; use Hearth\Booking\Domain\ReservationId; use Illuminate\Http\JsonResponse; final class ConfirmReservationController { public function __construct( private readonly ConfirmReservation $confirmReservation, ) { } public function __invoke(string $reservationId): JsonResponse { $this->confirmReservation->handle( new ConfirmReservationCommand( reservationId: new ReservationId($reservationId), confirmedAt: CarbonImmutable::now(), ), ); return new JsonResponse(status: 204); } }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Application; use Carbon\CarbonImmutable; use Hearth\Booking\Domain\ReservationId; final readonly class ConfirmReservationCommand { public function __construct( public ReservationId $reservationId, public CarbonImmutable $confirmedAt, ) { } }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Application; use Hearth\Booking\Domain\Money; use Hearth\Booking\Domain\PaymentAuthorization; use Hearth\Booking\Domain\ReservationId; interface Payments { public function authorize(ReservationId $id, Money $amount): PaymentAuthorization; }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Application; use Hearth\Booking\Domain\Reservations; final class ConfirmReservation { public function __construct( private readonly Reservations $reservations, private readonly Payments $payments, ) { } public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $authorization = $this->payments->authorize( $reservation->id, $reservation->totalPrice, ); $reservation->confirm($authorization, $command->confirmedAt); $this->reservations->save($reservation); } }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Infrastructure; use Hearth\Booking\Domain\Reservation; use Hearth\Booking\Domain\ReservationId; use Hearth\Booking\Domain\Reservations; final class EloquentReservations implements Reservations { public function withId(ReservationId $id): Reservation { $record = ReservationRecord::query()->findOrFail($id->toString()); return $record->toDomain(); } public function save(Reservation $reservation): void { ReservationRecord::query()->updateOrCreate( ['id' => $reservation->id->toString()], ReservationRecord::fromDomain($reservation), ); } }

Notice what each class does and doesn't know. The controller knows about HTTP and about the use case, nothing else. The use case knows about the domain and about interfaces (Reservations, Payments), not about Eloquent or HTTP. The Eloquent class knows about persistence and about the domain objects it converts to and from, not about controllers. ReservationRecord is the Eloquent model for the reservations table, and fromDomain() returns its columns as an array. ReservationId has a toString() method here, where the version in Patterns and Principles exposed only ->value.

The Reservations interface sits in the domain and EloquentReservations implements it, so the arrow between the application and infrastructure points inward even though the call goes outward. That is the dependency rule described in the next section: source code depends toward the business rules, whichever way the calls run. Payments has the same shape: Booking defines it, and the Payments module implements it.

ConfirmReservation::handle() is also the answer to the opening bug: it is the one method that decides what happens in which order, so the email step belongs after save() there, not in a controller or a model.

One note on the namespaces above, because they change later in the course. A namespace per layer, Presentation and Application and Domain, makes the three-layer model visible while you are learning it, which is why this lesson uses it. It is not how the Booking module ends up organized. From the next lesson on, Booking's classes sit flat under Hearth\Booking with a folder per use case, and Hearth\Booking\Infrastructure for the adapters. The layers survive the move; only the folder names stop announcing them.

The dependency rule

The rule that actually does the work in a layered design is simple to say and easy to violate: inner layers - the ones closer to business rules - never import outer layers, no matter how convenient it looks in the moment.

Here's the violation, and the fix, using the domain's cancellation logic.

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Domain; use Carbon\Carbon; use Hearth\Booking\Infrastructure\ReservationRecord; final class ReservationCancellation { public function refundAmountFor(ReservationRecord $record): int { $hoursUntilCheckIn = Carbon::now()->diffInHours($record->check_in, false); if ($hoursUntilCheckIn < 24) { return 0; } return $record->total_price_cents; } }

This class sits in the Domain namespace, but it imports an Eloquent record from Infrastructure. Two consequences follow. You cannot unit test the refund rule without building a full ReservationRecord, because the method signature demands one. And if the persistence layer changes its column names, this "domain" class breaks, even though the refund rule itself didn't change.

Here's the same rule with the dependency pointed the right way:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Domain; use Carbon\CarbonImmutable; interface CancellationPolicy { public function refundFor(Money $totalPrice, DateRange $stayDates, CarbonImmutable $now): Money; }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Domain; use Carbon\CarbonImmutable; final readonly class FreeWindowCancellationPolicy implements CancellationPolicy { public function __construct( private int $freeWindowHours = 24, ) { } public function refundFor(Money $totalPrice, DateRange $stayDates, CarbonImmutable $now): Money { $hoursUntilCheckIn = ($stayDates->checkIn->getTimestamp() - $now->getTimestamp()) / 3600; if ($hoursUntilCheckIn < $this->freeWindowHours) { return Money::zero($totalPrice->currency); } return $totalPrice; } }

FreeWindowCancellationPolicy is one implementation of the CancellationPolicy Strategy. It takes plain value objects and a timestamp, and returns a Money value object. It doesn't know a database exists. Testing it is a matter of constructing a DateRange, a Money, and a CarbonImmutable, then asserting on the result, no framework required. The application layer, when it eventually needs a refund amount, calls the policy and passes it what it needs.

Onion Architecture, briefly

Jeffrey Palermo described Onion Architecture in July 2008, in the first of four blog posts, using rings instead of a stack: the domain model in the center, interfaces for saving and retrieving it around that, and UI, infrastructure and tests on the outside. The dependency rule is the same as in the three-layer model: code can depend on rings closer to the center and never on rings further out. Hexagonal and Clean Architecture, covered later in this chapter, share that rule with their own vocabulary.

Reading an unfamiliar codebase by layer

When you open a codebase you didn't write and need to work in it fast, two questions tell you more than reading files top to bottom.

Which way the dependencies point. Open a class that holds business rules and read its use statements. If it imports Eloquent or an HTTP request object, the dependency rule is already broken here, whatever the folder structure claims.

Whether the structure is horizontal or vertical. Folders named Controllers/, Services/, Repositories/ are a horizontal cut, one folder per layer, features scattered across all of them. Folders named Booking/, Housekeeping/, Payments/ are a vertical cut, one folder per feature, with layering nested inside. Vertical means someone decided the feature, not the layer, is the unit that should stay together, which is what Vertical Slice Architecture commits to all the way.

Common mistakes

Layering for its own sake. A request passes through a controller, a service, a manager, a handler, and a repository, and four of those five classes do nothing but call the next one with the same arguments. Nobody decided to build five layers; each one got added the day someone needed "just one more place to put a method". The fix is checking, before adding one, whether the concern you're adding has a genuinely different reason to change from the layers you already have.

Leaky layers. The folder structure is correct and the imports aren't. A class sits in Domain/ and imports an Eloquent model. The folder names lie about what the code does, and a reviewer scanning the directory tree comes away with false confidence. Catching this means reading imports.

Cargo-culting one architecture everywhere. A team reads about Hexagonal Architecture, decides "we're doing Hexagonal now", and applies the full ports-and-adapters ceremony to an admin CRUD screen with no business rules worth protecting.

The one thing to remember

A layer is a group of code with one reason to change and a narrow surface to its neighbors, and the dependency rule says the layers closer to your business rules never import the layers further from them. Hexagonal, Clean and Onion share that one rule, and Vertical Slice Architecture, later in this chapter, changes which folder a file sits in rather than which direction its imports point.

Course Content