Lesson 10 of 17 · How We Think About Code
Framework Coupling vs Framework Decoupling
What a framework is for
All frameworks are opinionated general solutions that try to help us build a product. They save us time so that we don't have to write code manually, and we can focus on the real problem, which is solving business-related problems and automating processes.
The framework gives you HTTP routing, request validation, ORM, queues, mailers, cache, file storage, sessions, auth scaffolding, and a hundred other small pieces. In exchange, you ship faster than you would from a blank repo. Most of the time it's a good trade.
It stops being a good trade when the framework stops being a tool and starts being the shape of the product itself.
The slip from "using" to "absorbed by"
As developers learn a framework, they start to like it and lean on it harder. They write code that uses the framework to the fullest, which means depending on it to drive development and solve the problem instead of solving it themselves.
This is what's called framework coupling, or coupling yourself to the framework. Every project I've worked on has had it, and the phrase is fuzzy enough that people mean different things by it. The rest of this lesson pins it to one piece of code.
What framework coupling looks like in code
The obvious version is the fat controller: every facade and helper the framework offers, called in sequence from one method. Earlier, the hotel reservation controller had grown into exactly that: validation, a lock, business rules, pricing, coupons, persistence, an email, and an audit log, all in one method. That code is coupled in a way nobody needs a lesson to see. This lesson looks at the less obvious version. That fix moved the sequence into a command handler and the rules onto the model. Here is that handler again, plus one line a teammate added when the rooms table got slow: the room is cached for thirty minutes.
<?php
declare(strict_types=1);
namespace App\Reservations\CreateReservation;
use App\Reservations\Coupon\Coupon;
use App\Reservations\Room\Room;
use App\Reservations\Room\RoomLock;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
final readonly class CreateReservationCommandHandler
{
public function __construct(
private RoomLock $lock,
private Dispatcher $events,
) {}
public function handle(CreateReservationCommand $command): CreateReservationResult
{
return $this->lock->around($command->roomId, $command->stay, function () use ($command): CreateReservationResult {
$room = Cache::remember(
"room:{$command->roomId}",
30,
fn (): Room => Room::findOrFail($command->roomId),
);
$coupon = Coupon::findRedeemable($command->couponCode);
$priceCents = $room->priceFor($command->stay);
$priceCents = $coupon?->applyTo($priceCents) ?? $priceCents;
$reservation = $room->reserve($command->stay, $command->guestId, $priceCents);
$coupon?->redeem();
$this->events->dispatch(new ReservationRequested($reservation->id, $command->guestId));
return new CreateReservationResult($reservation->id);
});
}
}And the model that holds the rules, with the factory trait the test further down needs:
<?php
declare(strict_types=1);
namespace App\Reservations\Room;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Stay;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* @use HasFactory<RoomFactory>
*/
final class Room extends Model
{
use HasFactory;
public function reservations(): HasMany
{
return $this->hasMany(Reservation::class);
}
public function priceFor(Stay $stay): int
{
return $this->nightly_rate_cents * $stay->nights();
}
public function reserve(Stay $stay, int $guestId, int $priceCents): Reservation
{
if ($stay->nights() > $this->max_nights) {
throw new StayTooLongException($this, $stay);
}
if ($this->reservations()->overlapping($stay)->exists()) {
throw new RoomAlreadyReservedException($this, $stay);
}
return $this->reservations()->create([
'guest_id' => $guestId,
'check_in' => $stay->checkIn,
'check_out' => $stay->checkOut,
'total_price_cents' => $priceCents,
]);
}
}By the standard of the fat controller this is the good version. The controller is thin, the handler reads like the business process, and the rules live on the object that owns them. That was the right trade for the point that fix was making, and it's still the right first step.
Now read it for a different question: what does this code know about the framework?
Room extends Model. The thing that holds the business rules is an Eloquent model. It cannot load, save, or check its reservations without a database connection behind it.Room::findOrFailandCoupon::findRedeemableare static calls into Eloquent's query builder. The handler decides how rooms are loaded, not just that they are.$this->reservations()->overlapping($stay)->exists()runs a query in the middle of a business rule. The rule "a room cannot be double-booked" is expressed as SQL.$this->reservations()->create([...])means "make a reservation" is a mass-assignment call.Cache::remember(..., 30, ...)goes through a facade, and the30means whatever the installed version of Laravel says it means.Illuminate\Contracts\Events\Dispatcheris the framework's event contract, so the business layer's constructor signature names Laravel.
Moving the code out of the controller made it readable. It did not make it independent. The reservation logic still cannot run or be tested without the framework booted underneath it. The framework is the material this code is made of.
Why is this a problem?
For a long-lived product, three costs show up:
Tool and language upgrades slow down and become harder to manage when the framework's API is used everywhere.
The risk of breaking the product is higher, because the required changes affect the whole product.
It takes more time to implement the changes and test all of them.
These costs don't feel like a big deal until they land.
I've watched a team of five or more people upgrade Laravel from 5.3 to 5.8 over a few months, including testing it manually on separate servers due to the size of the fintech product I was working on. The upgrade most likely cost thousands of dollars, if I had to guess. None of that work added a feature, fixed a bug a customer cared about, or moved the product forward. It was the cost of having let the framework's API live everywhere in the codebase.
Two of those costs can be shown in code rather than described.
Proof one: the test
The rule under test is "a room that is already reserved for those dates refuses a second reservation." It's a comparison between two date ranges. Here's what it takes to test it against the Room above:
<?php
declare(strict_types=1);
namespace Tests\Feature\Reservations;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Room\Room;
use App\Reservations\Room\RoomAlreadyReservedException;
use App\Reservations\Stay;
use DateTimeImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
final class RoomTest extends TestCase
{
use RefreshDatabase;
#[Test]
public function it_refuses_a_stay_that_overlaps_an_existing_reservation(): void
{
$room = Room::factory()->create(['max_nights' => 14, 'nightly_rate_cents' => 12_000]);
Reservation::factory()->create([
'room_id' => $room->id,
'check_in' => '2026-10-01',
'check_out' => '2026-10-05',
]);
$this->assertThrows(
fn () => $room->reserve(
new Stay(new DateTimeImmutable('2026-10-03'), new DateTimeImmutable('2026-10-06')),
guestId: 7,
priceCents: 36_000,
),
RoomAlreadyReservedException::class,
);
$this->assertDatabaseCount('reservations', 1);
}
}To check whether two date ranges overlap, this test runs every migration through RefreshDatabase, needs a Room factory and a Reservation factory, and needs a database to be reachable from the test process. If the migration for a table nothing in this test cares about breaks, this test breaks. The rule itself is two lines long.
Proof two: the upgrade
The Laravel 5.8 upgrade guide, which sits inside the 5.3 to 5.8 range from the story above, has this under "High Impact Changes", marked "Likelihood Of Impact: Very High":
In order to allow a more granular expiration time when storing items, the cache item time-to-live has changed from minutes to seconds. The
put,putMany,add,rememberandsetDefaultCacheTimemethods of theIlluminate\Cache\Repositoryclass and its extended classes, as well as theputmethod of each cache store were updated with this changed behavior.
The Cache::remember("room:{$command->roomId}", 30, ...) line in the handler still compiles after the upgrade. Nothing in the test suite asserts how long a room stays cached, so every test still passes. It now caches the room for thirty seconds instead of thirty minutes, and the only way to find out is to notice the rooms table getting slow again. The fix is to grep for every cache call in the codebase and reason about each one. In a codebase where handlers, models, and controllers all talk to the cache directly, that grep returns hits across the whole codebase.
The same shape shows up outside the framework proper. Carbon, the date library Laravel hands you on every timestamp column and every now(), changed its diffIn* methods in version 3. From the release notes: "Changed diffIn* methods to return float and relative diff ($absolute = false by default)". So $checkOut->diffInDays($checkIn) returned 4 on Carbon 2 and returns -4.0 on Carbon 3, in every place that ever called it. I watched a product upgrade Carbon to the latest version and it needed changes across the whole codebase, because every date in the business code was a Carbon object. It was a scary upgrade for the size of the version bump. The Stay value in this lesson is built on PHP's own DateTimeImmutable and counts nights with diff()->days, the way the fat controller did, so Carbon's change would have stopped at the adapters.
The way out: program against contracts
To avoid these problems and make it easier, there's a method where you use interfaces instead of direct implementations everywhere.
The idea is that you don't use the implementation class all over the codebase. You use interfaces, and then you tell the container which interface should inject which implementation, and where, in case a specific context is required. For example: use the Eloquent-backed room lookup in production, use an in-memory one in tests, use a different one inside the module that syncs availability to booking sites.
It may sound like a strange idea: "why would anyone want to build their own packages when we have those as framework components out of the box?" Framework components are generic solutions by design. They aren't built for the specific business you're working on.
I'm not suggesting you should build your own framework. The practical version is more modest: be aware of which packages you use, and don't let any of them touch the business code directly.
Some of the changes you may need in some of the packages may get declined upstream, so you would have to rework the implementation slightly to fit the business requirements. Reworking around that is a lot more effort when the framework is everywhere than when it's behind a small set of seams - the few places where business code and framework code actually touch.
What framework decoupling looks like in code
Here's the same reservation feature, written so the business logic doesn't know what framework it lives in.
The handler orchestrates the workflow against ports: interfaces the business layer defines and the framework layer fulfils. Every dependency in its constructor is one of those interfaces.
<?php
declare(strict_types=1);
namespace App\Reservations\CreateReservation;
use App\Reservations\Coupon\Coupons;
use App\Reservations\DomainEvents;
use App\Reservations\Reservation\Reservations;
use App\Reservations\Room\RoomLock;
use App\Reservations\Room\Rooms;
final readonly class CreateReservationCommandHandler
{
public function __construct(
private Rooms $rooms,
private Coupons $coupons,
private Reservations $reservations,
private RoomLock $lock,
private DomainEvents $events,
) {}
public function handle(CreateReservationCommand $command): CreateReservationResult
{
return $this->lock->around($command->roomId, $command->stay, function () use ($command): CreateReservationResult {
$room = $this->rooms->withId($command->roomId);
$coupon = $this->coupons->findRedeemable($command->couponCode);
$priceCents = $room->priceFor($command->stay, $coupon);
$reservation = $room->reserve(
$this->reservations->nextId(),
$command->stay,
$command->guestId,
$priceCents,
);
$this->reservations->save($reservation);
if ($coupon) {
$coupon->redeem();
$this->coupons->save($coupon);
}
$this->events->dispatch(new ReservationRequested($reservation->id, $command->guestId));
return new CreateReservationResult($reservation->id);
});
}
}The room is a plain object. It's given the stays already booked against it when it's loaded, so the double-booking rule is a comparison in memory instead of a query.
<?php
declare(strict_types=1);
namespace App\Reservations\Room;
use App\Reservations\Coupon\Coupon;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Stay;
final class Room
{
/**
* @param list<Stay> $bookedStays
*/
public function __construct(
public readonly int $id,
public readonly int $maxNights,
public readonly int $nightlyRateCents,
private array $bookedStays,
) {}
public function priceFor(Stay $stay, ?Coupon $coupon = null): int
{
$priceCents = $this->nightlyRateCents * $stay->nights();
return $coupon?->applyTo($priceCents) ?? $priceCents;
}
public function reserve(int $reservationId, Stay $stay, int $guestId, int $priceCents): Reservation
{
if ($stay->nights() > $this->maxNights) {
throw new StayTooLongException($this, $stay);
}
foreach ($this->bookedStays as $booked) {
if ($booked->overlaps($stay)) {
throw new RoomAlreadyReservedException($this, $stay);
}
}
$this->bookedStays[] = $stay;
return new Reservation(
id: $reservationId,
roomId: $this->id,
guestId: $guestId,
stay: $stay,
totalPriceCents: $priceCents,
);
}
}The ports the business code talks to. Each one is named after the business concept, not after the technology behind it. Reservations::nextId() exists because the plain Reservation needs its id before anything stores it. How the adapter mints one is its own business: Postgres has sequences for it, and on MySQL the usual answer is a UUID or ULID column, which this lesson skips to keep the ids int.
<?php
declare(strict_types=1);
namespace App\Reservations\Room;
interface Rooms
{
public function withId(int $id): Room;
}<?php
declare(strict_types=1);
namespace App\Reservations\Reservation;
interface Reservations
{
public function nextId(): int;
public function save(Reservation $reservation): void;
}<?php
declare(strict_types=1);
namespace App\Reservations;
interface DomainEvents
{
public function dispatch(object $event): void;
}The pieces not shown follow the same shape. Coupons has findRedeemable() and save(), and Coupon is a plain object with applyTo() and redeem(). Reservation is a plain object that takes its int id from Reservations::nextId() in its constructor. Stay gains an overlaps() method next to nights(). RoomLock from the earlier controller becomes an interface, and the class that wrapped the Symfony lock factory becomes its implementation. The two exceptions keep their names and still render themselves as the 422 and 409 responses. The module's service provider maps the command to its handler and binds each port to its implementation, so the wiring is one greppable file.
One implementation of a port, which this style calls an adapter, to show where the framework went. The cache key and its lifetime live in one enum, so there is exactly one place that knows what the number means:
<?php
declare(strict_types=1);
namespace App\Reservations\Infrastructure;
enum ReservationCacheKey: string
{
case ROOM = 'room';
public function key(int $id): string
{
return "{$this->value}:{$id}";
}
public function ttl(): int
{
return match ($this) {
self::ROOM => 30 * 60,
};
}
}This is the Eloquent-backed Rooms, and it's where the cache call and the findOrFail from the coupled handler now live:
<?php
declare(strict_types=1);
namespace App\Reservations\Infrastructure;
use App\Reservations\Room\Room;
use App\Reservations\Room\Rooms;
use App\Reservations\Stay;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Cache\Repository;
final readonly class EloquentRooms implements Rooms
{
public function __construct(
private Repository $cache,
) {}
public function withId(int $id): Room
{
$record = $this->cache->remember(
ReservationCacheKey::ROOM->key($id),
ReservationCacheKey::ROOM->ttl(),
fn (): RoomRecord => RoomRecord::findOrFail($id),
);
$bookedStays = ReservationRecord::query()
->where('room_id', $id)
->where('check_out', '>=', CarbonImmutable::now()->toDateString())
->get()
->map(fn (ReservationRecord $reservation): Stay => new Stay($reservation->check_in, $reservation->check_out))
->all();
return new Room(
id: $record->id,
maxNights: $record->max_nights,
nightlyRateCents: $record->nightly_rate_cents,
bookedStays: $bookedStays,
);
}
}RoomRecord and ReservationRecord are the Eloquent models, renamed so they don't collide with the plain objects. They only load and save rows now, with no business rules on them. ReservationRecord casts check_in and check_out to immutable_date, so the values handed to Stay are already DateTimeImmutable instances. Only the room record is cached, because caching the whole Room would cache its booked stays, and availability has to be read live. The TTL reads 30 * 60 because it was written after the 5.8 upgrade, and when the next cache change lands, ReservationCacheKey::ttl() is the whole search space.
The business layer (CreateReservationCommandHandler, Room, the ports) doesn't know that Laravel exists. It doesn't know whether rooms come from MySQL, Elasticsearch, a cache, or an array. It doesn't know whether the lock is Symfony's, Laravel's, or a no-op. It doesn't know whether the event will be handled in-process, by a queue, or not at all.
The framework layer (the controller, the request, EloquentRooms and its siblings, the lock implementation, the listeners) is allowed to know all those things, because knowing them is its job.
Now the same test from earlier, against the plain Room:
<?php
declare(strict_types=1);
namespace Tests\Unit\Reservations;
use App\Reservations\Room\Room;
use App\Reservations\Room\RoomAlreadyReservedException;
use App\Reservations\Stay;
use DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
final class RoomTest extends TestCase
{
#[Test]
public function it_refuses_a_stay_that_overlaps_an_existing_reservation(): void
{
$room = new Room(
id: 1,
maxNights: 14,
nightlyRateCents: 12_000,
bookedStays: [
new Stay(new DateTimeImmutable('2026-10-01'), new DateTimeImmutable('2026-10-05')),
],
);
$this->assertThrows(
fn () => $room->reserve(
42,
new Stay(new DateTimeImmutable('2026-10-03'), new DateTimeImmutable('2026-10-06')),
guestId: 7,
priceCents: 36_000,
),
RoomAlreadyReservedException::class,
);
}
}Same base test case, same rule, and nothing in it touches a database. There are no migrations to run, no factories to maintain, and no rows to assert on, because the object under test was built with new. The test for the handler has the same shape: bind an in-memory Rooms holding one room and an in-memory Reservations that hands out ids and keeps what it's given, call Event::fake(), resolve the handler from the container, and assert ReservationRequested was dispatched with the new reservation's id.
The structure of the code and the framework in the example doesn't matter much. What matters is the seam holds: the framework never reaches past it into the business side.
What you actually buy
Faster, safer upgrades. When the framework, or a library it ships with, changes its cache API, the ORM, the date library, or the event dispatcher, the only code that has to change is the implementation behind the interface. The business code doesn't notice. The 5.3 to 5.8 upgrade becomes a much smaller piece of work when "the framework" lives in the adapters behind the ports instead of in the middle of every handler.
Real testing benefits. You saw the two versions of
RoomTest. The pure-business tests are fast, they test one unit at a time, and you can wire in testing-specific implementations of any port. You'll still have tests that exercise the real implementations (Eloquent, the lock store, the mailer). Those live in a separate suite and can run less often, because they're slower.Reuse across entry points. The same
CreateReservationCommandcan be dispatched from a controller, an Artisan command that imports bookings from a channel manager, a queue worker, or a test, with no change. Without the seam, the second entry point copies the handler's body, which is the duplication problem in disguise.Isolated change. When the business asks for a new rule, say a room needs one empty night between two stays for cleaning, the change lands in
Room::reserveand in one unit test. No handler, controller, or adapter changes.
"Why use a framework if you're not going to use it?"
You will use the components of the framework. Not all of them, and not the way the framework's convention says to use them.
The framework's job, in this style, is:
Routing requests to controllers.
Booting up the container and wiring interfaces to implementations.
Providing the working implementations behind those interfaces (Eloquent behind
RoomsandReservations, its event dispatcher behindDomainEvents, the mailer for whatever the listeners need, and so on).Handling cross-cutting things you don't want to write yourself: middleware, sessions, validation, queue workers, scheduling.
The framework's job is not:
Defining what the business concepts mean.
Living in the middle of every business operation.
Dictating where business logic goes.
What this isn't
Building your own framework is off the table here. That's a bigger, longer commitment than the coupling problem it's meant to solve. Hiding everything behind interfaces is too: some things, especially in the framework layer, are fine talking to concrete classes directly, and the line lives where the business logic begins.
Decoupling earns its place when the product is going to stick around, the domain is genuinely complex, the team is big enough that people collide, and upgrades actually happen. A small brand site, a side project, a throwaway tool: the earlier version of the reservation handler is fine for those, exactly because the costs above never get a chance to land. This is a context-shaped decision.
The one thing to remember
Frameworks are tools, not architectures. Use the tool for what it's good at, and don't let it write your domain for you. The codebases that survive the longest are the ones where the framework lives in a thin layer at the edges, and the business lives in plain PHP objects in the middle.
When you can describe what your code does without saying the framework's name, you're decoupled. When you can't, you're coupled, and the cost is being paid quietly on every upgrade and every change.
Related Links
- Screaming ArchitectureRobert C. Martin on why a system's structure should reveal its use cases, not its framework.
- A simple recipe for framework decouplingMatthias Noback's three rules for keeping business code out of framework classes.
- FrameworkismAaron Stannard on the trap of framework-first thinking.
- Recipes For DecouplingMatthias Noback's step-by-step recipes for decoupling from the framework, ORM, and test framework.
- Decoupling the Model from the FrameworkMatthias Noback's talk on keeping the domain model free of framework code.