Lesson 9 of 15 · Living With an Architecture
Where Framework Code Is Allowed to Live
An argument that shouldn't need to happen
Two engineers on a hotel booking team are reviewing a pull request for CancelReservation. The diff adds a CarbonImmutable $now parameter to Reservation::cancel(). One engineer approves it. The other blocks it: Carbon is a Laravel class, and the Hexagonal Architecture lesson said no framework in the core.
Both have read the same lesson. Both agree with the dependency rule: dependencies point inward, the domain doesn't import the framework. They disagree about what it actually covers, because "keep the framework out of the core" was never a precise instruction. It was a slogan standing in for a judgment call, and the two engineers are making that judgment differently on the same line of code.
The test
"Is this Laravel?" is the wrong question, because Laravel isn't one thing. A Laravel 13 composer.json pulls in dozens of packages: some are framework glue (illuminate/routing, illuminate/container), some are ordinary PHP libraries that ship in the same box (nesbot/carbon, symfony/console).
The question that actually decides it: if this package disappeared tomorrow, what would you have to rewrite, and would the business rule still be expressible without it?
Apply it to Illuminate\Database\Eloquent\Model. The rule that a confirmed reservation can't be re-priced without a re-quote doesn't change if Eloquent vanishes, but the code enforcing it does, because on an Eloquent model the rule and the persistence are the same object. It fails.
Apply it to Carbon\CarbonImmutable. You'd swap the type hint for PHP's native \DateTimeImmutable, which Carbon already extends, and lose a few convenience methods. The rule that cancellations inside the policy window get no refund is about time until check-in, not about which class counts them. It passes, with a caveat below.
Applying the test, piece by piece
Here's the verdict for the parts of a Laravel 13 application a booking system actually uses. "Core" means the aggregate and its domain rules; "edges" means controllers, console commands, queue jobs, Form Requests, and repository implementations, the driving and driven adapters from the Hexagonal lesson.
Piece | Where it belongs | Why |
|---|---|---|
Eloquent models | Edges (infrastructure adapters) | Fails the test: remove Eloquent, rewrite the mapping code from scratch. The Hexagonal lesson's own pitfall list already says it: no Eloquent in the core, not no Eloquent at all. |
Query builder ( | Edges | Same failure mode as Eloquent, how a repository implementation talks to a table. The aggregate never sees a query. |
Form Requests | Edges (driving adapter) | Shapes and authorizes an HTTP payload into a command. Remove it, hand-roll the parsing, and the command handler underneath doesn't change. |
Validation rules ( | Edges | Good for checking a payload is well-formed: a string, an email, a date in the future. An invariant that has to hold no matter who calls the code belongs on the value object or the aggregate, because a queue job never runs a Form Request. |
Facades ( | Edges | A static-looking call that resolves from the container behind the scenes. The core asks for a port instead, the way |
Service container and its bindings | Edges (bootstrap) | Wires ports to adapters from outside the core. The core is something the container constructs; it never calls the container itself. |
| Arguable, see below | |
| Edges | A global read of Laravel's config repository. A rule that depends on a configured value gets that value passed in by the handler; the aggregate never calls it. |
| Edges | Resolves the session's user through Laravel's auth manager. The handler passes a |
| Arguable, see below | |
The exception handler | Edges |
|
Events and listeners | Split | The event object is a plain PHP object the aggregate creates; Laravel's dispatch sits behind the |
Queued jobs ( | Edges (driving adapter) | A third way of triggering the same use case, alongside HTTP and CLI. The job's |
Ten of these rows settle on the same answer: if the package is how the application core talks to the outside world, it's edges. The two marked arguable, plus one case a table row can't express, are where the question doesn't resolve as cleanly.
Three cases the table can't settle
Carbon and CarbonImmutable. nesbot/carbon is a standalone library, maintained independently of the framework, that Laravel's composer.json happens to require (^3.8.4 as of the current Laravel 13 release). Symfony projects and plain PHP scripts use it too. Layered Architecture and the Dependency Rule already rules on this, on purpose: it moves the cancellation logic off an Eloquent model and a static Carbon::now() call, onto a policy whose refundFor(Money $totalPrice, DateRange $stayDates, CarbonImmutable $now): Money takes CarbonImmutable straight in the signature, not \DateTimeImmutable. Carbon passes the disappearance test, so there was never a reason to hide it behind a native interface. Allowed in the core, because banning it buys nothing beyond reimplementing diffInDays() on \DateTimeImmutable.
Illuminate\Support\Collection. Shipped separately as illuminate/collections, requiring only illuminate/conditionable, illuminate/contracts and illuminate/macroable (plus PHP polyfills), not the container, not HTTP, not Eloquent. By the disappearance test it reads the same as Carbon: swap it for array_filter() and array_map() chains and the rule stays as expressible. Allowed, with less confidence than Carbon, because the two packages don't share a history: Carbon is maintained outside Laravel entirely, while illuminate/collections is built and released alongside the rest of the framework.
Eloquent as a persistence layer behind a repository. This is where "no framework in the core" gets misapplied past its boundary. EloquentReservations, the Hexagonal lesson's repository implementation, works through ReservationRecord, an Eloquent Model, on every line, and that isn't a violation: its entire job is translating between the domain object and the table, and it lives in Hearth\Booking\Infrastructure, outside the core by the dependency rule that lesson already drew. The test applies one layer over: if Eloquent disappeared, EloquentReservations gets rewritten and nothing else does. Hand-rolling a query layer to keep the word "Eloquent" out of every file is ceremony: a persistence system built to avoid a dependency the domain was never reachable from.
A worked example
The pull request's Reservation::cancel(string $reason, CarbonImmutable $now): Money settles the argument that opened this lesson. Its body hands the value straight on: $refund = $this->cancellationPolicy->refundFor($this->totalPrice, $this->stayDates, $now);. Carbon shows up exactly in the shape this lesson has been arguing for, a value handed in, not reached for.
The interesting version of the same mistake lives one level down, in whichever CancellationPolicy implementation refundFor() calls. $now is a parameter there too, which makes the leak easier to write by accident: the correct value is sitting in the method signature, and it's still possible to ignore it.
Here's a version of FreeWindowCancellationPolicy a careful engineer might write first, the kind that reads clean in isolation and only shows its problem in the pull request that tries to unit test it:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Reservation;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\Money;
final readonly class FreeWindowCancellationPolicy implements CancellationPolicy
{
public function refundFor(Money $totalPrice, DateRange $stayDates, CarbonImmutable $now): Money
{
$freeWindowHours = config('booking.free_cancellation_window_hours', 24);
return Carbon::now()->diffInHours($stayDates->checkIn) >= $freeWindowHours
? $totalPrice
: Money::zero($totalPrice->currency);
}
}Run this through the disappearance test. Carbon::now() calls Carbon's global clock directly, the exact call the Clock port exists to replace, and it does so despite the method already receiving a CarbonImmutable $now it never touches. A test asserting "cancelling 25 hours before check-in refunds the full amount" can't control what "now" is without setting Carbon's global test clock. config('booking.free_cancellation_window_hours') is worse: the window comes from Laravel's config repository, so no test of the refund rule runs without a booted application. Both hide a required input behind a global call, and removing either one forces the refund rule itself to be rewritten.
The corrected version is the Layered Architecture lesson's policy, now in Booking's Reservation namespace. It uses the value the interface already hands it, and takes the window through its constructor:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Reservation;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\Money;
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;
}
}A window that genuinely needs to be configurable stays a constructor argument: the service provider reads the config value once, at the edge, and passes it in when it binds the policy. A test passes whatever window it needs.
$now reaches the policy because Reservation::cancel() was handed one, and cancel() gets it from a handler using the Clock port from the Hexagonal lesson:
<?php
declare(strict_types=1);
namespace Hearth\Booking\CancelReservation;
use Hearth\Booking\Clock;
use Hearth\Booking\Dispatcher;
use Hearth\Booking\Money;
use Hearth\Booking\Reservation\Reservations;
final readonly class CancelReservationCommandHandler
{
public function __construct(
private Reservations $reservations,
private Clock $clock,
private Dispatcher $dispatcher,
) {}
public function handle(CancelReservationCommand $command): Money
{
$reservation = $this->reservations->withId($command->reservationId);
$refund = $reservation->cancel($command->reason, $this->clock->now());
$this->reservations->save($reservation);
foreach ($reservation->releaseEvents() as $event) {
$this->dispatcher->dispatch($event);
}
return $refund;
}
}Nothing here is new: the Reservations, Clock and Dispatcher ports from the Hexagonal lesson, feeding a CarbonImmutable into a method that already expected one. CancelReservationCommand is a final readonly class holding a ReservationId $reservationId and a string $reason.
Testing "cancelling 25 hours before check-in refunds the full amount" now means constructing the policy, calling refundFor() with a $now 25 hours before check-in, and asserting on the returned Money. No config array, no static clock, no container.
Making the rule hold without arguing about it every time
A rule that lives in a reviewer's head gets applied inconsistently, because it depends on which reviewer looks at which diff. Two tools turn it into something CI checks on every push.
Deptrac defines architectural layers as regex collectors over fully qualified class names, then permits or forbids dependencies between them in a ruleset. A layer may depend only on the layers its ruleset line lists. A deptrac.yaml for the Hearth modules that encodes this lesson's verdicts and the module rule:
# deptrac.yaml
deptrac:
paths:
- ./Hearth
layers:
- name: Booking
collectors:
- type: classNameRegex
value: '#^Hearth\\Booking\\(?!(Infrastructure\\|Tests\\|BookingServiceProvider$|GuestProfiles$|GuestSummary$|GuestId$))(?!.*(Controller|Responder|Request|Resource|ConsoleCommand|ReservationRequested|ReservationConfirmed|ReservationCancelled|GuestCheckedIn)$)#'
- name: BookingEdges
collectors:
- type: classNameRegex
value: '#^Hearth\\Booking\\(Infrastructure\\|BookingServiceProvider$|.*(Controller|Responder|Request|Resource|ConsoleCommand)$)#'
- name: BookingEvents
collectors:
- type: classNameRegex
value: '#^Hearth\\Booking\\.*(ReservationRequested|ReservationConfirmed|ReservationCancelled|GuestCheckedIn)$#'
- name: BookingContracts
collectors:
- type: classNameRegex
value: '#^Hearth\\Booking\\(GuestProfiles|GuestSummary|GuestId)$#'
- name: Housekeeping
collectors:
- type: classNameRegex
value: '#^Hearth\\Housekeeping\\#'
- name: Notifications
collectors:
- type: classNameRegex
value: '#^Hearth\\Notifications\\#'
- name: GuestProfile
collectors:
- type: classNameRegex
value: '#^Hearth\\GuestProfile\\#'
- name: Payments
collectors:
- type: classNameRegex
value: '#^Hearth\\Payments\\#'
- name: Pricing
collectors:
- type: classNameRegex
value: '#^Hearth\\Pricing\\#'
- name: Framework
collectors:
- type: classNameRegex
value: '#^Illuminate\\(?!Support\\Collection$)#'
- name: Collections
collectors:
- type: classNameRegex
value: '#^Illuminate\\Support\\Collection$#'
ruleset:
Booking: [BookingEvents, BookingContracts, Collections]
BookingEdges: [Booking, BookingEvents, BookingContracts, Framework]
BookingEvents: ~
BookingContracts: ~
Housekeeping: [Framework]
Notifications: [Framework, BookingEvents]
GuestProfile: [Framework, BookingContracts]
Payments: [Framework]
Pricing: [Framework]
Collections: ~
Framework: ~Booking is the core: everything under Hearth\Booking except the edges, the tests, the events and the consumer-defined contracts. It is not listed as depending on Framework (only on Collections, the verdict above), so an Illuminate\Database\Eloquent\Model import inside Hearth\Booking\Reservation fails the build. The other modules may not depend on Booking at all, with two exceptions: Notifications (a listener) may import BookingEvents, and GuestProfile (a provider) may import BookingContracts. Run vendor/bin/deptrac analyse in CI.
PHPArkitect does a similar job with PHP instead of YAML, through rule classes like NotDependsOnTheseNamespaces, applied to classes matching a namespace. A phparkitect.php config file for the same rules:
<?php
declare(strict_types=1);
use Arkitect\ClassSet;
use Arkitect\CLI\Config;
use Arkitect\Expression\ForClasses\NotDependsOnTheseNamespaces;
use Arkitect\Expression\ForClasses\NotHaveNameMatching;
use Arkitect\Expression\ForClasses\NotResideInTheseNamespaces;
use Arkitect\Expression\ForClasses\ResideInOneOfTheseNamespaces;
use Arkitect\Rules\Rule;
return static function (Config $config): void {
$classSet = ClassSet::fromDir(__DIR__.'/Hearth');
$rules = [
Rule::allClasses()
->that(new ResideInOneOfTheseNamespaces('Hearth\Booking'))
->andThat(new NotResideInTheseNamespaces('Hearth\Booking\Infrastructure', 'Hearth\Booking\Tests'))
->andThat(new NotHaveNameMatching('*Controller'))
->andThat(new NotHaveNameMatching('*Responder'))
->andThat(new NotHaveNameMatching('*Request'))
->andThat(new NotHaveNameMatching('*Resource'))
->andThat(new NotHaveNameMatching('*ConsoleCommand'))
->andThat(new NotHaveNameMatching('BookingServiceProvider'))
->should(new NotDependsOnTheseNamespaces(['Illuminate'], ['Illuminate\Support\Collection']))
->because('the Booking core stays free of Illuminate; the edges are the exception'),
];
$modules = ['Booking', 'Housekeeping', 'Payments', 'Pricing', 'Notifications', 'GuestProfile'];
$allowedFromBooking = [
'Notifications' => ['Hearth\Booking\ConfirmReservation\ReservationConfirmed'],
'GuestProfile' => ['Hearth\Booking\GuestProfiles', 'Hearth\Booking\GuestSummary', 'Hearth\Booking\GuestId'],
];
foreach ($modules as $module) {
$otherModules = array_map(
static fn (string $other): string => "Hearth\\{$other}",
array_values(array_diff($modules, [$module])),
);
$rules[] = Rule::allClasses()
->that(new ResideInOneOfTheseNamespaces("Hearth\\{$module}"))
->should(new NotDependsOnTheseNamespaces($otherModules, $allowedFromBooking[$module] ?? []))
->because("{$module} imports nothing from another module except a listener's event or a provider's contract");
}
$config->add($classSet, ...$rules);
};Reaching for PHPArkitect over Deptrac is mostly a matter of preferring rules as PHP, with the because() clause forcing every rule to carry its own justification in the codebase.
For the finer-grained calls, no Carbon::now() inside the Booking namespace and no config() or auth(), neither tool is enough: PHPArkitect does not see function calls, and neither config can tell Carbon::now() from other Carbon uses. PHPStan's spaze/phpstan-disallowed-calls extension bans them per path, with an allow-list for SystemClock, the one adapter where the static call belongs.
Pitfalls
Writing the CI rule before deciding the verdict. A ruleset banning all of Illuminate\* from the core also flags Illuminate\Support\Collection after a team has already decided that one's fine. Decide the verdict first; write the rule to match it.
Using a validation rule to enforce a business invariant. The rule that the guest count fits the room's capacity has to hold everywhere a reservation gets created, not just behind whichever Form Request happens to run first.
The one thing to remember
The deciding question is whether removing the package means rewriting the business rule, or just its wiring. Answer that per class, write the answer into a Deptrac or PHPArkitect ruleset, and the next pull request argument becomes a build failure instead of a disagreement.
Related Links
- Deptracthe layer-rule enforcement tool this lesson's configuration example is built on.
- PHPArkitectthe PHP-native alternative to Deptrac for the same class of rule, used for the NotDependsOnTheseNamespaces example.
- nesbot/carbon on Packagistconfirms Carbon ships and versions independently of Laravel, the basis for this lesson's verdict on CarbonImmutable.
- Validation | Laravel 13.xthe current ValidationRule interface this lesson's table references.