Skip to content

Lesson 20 of 45 · Behavior and Variation

The Specification Pattern

Intermediate•
lesson•
October 29, 2026•
~10 min read

The rule that's everywhere and nowhere

A business rule shows up in three places in your codebase:

  • The eligibility check before showing a room in search results.

  • The query that selects available rooms for a stay.

  • The validation that fires when a guest actually tries to reserve one.

Each place has its own version of the rule. They start identical, and after enough unrelated edits they've drifted, slightly. The eligibility check says "available rooms for the date range". The query says "rooms marked Available", with no date check. The validation says "available rooms for the date range that fit the guest count". Neither the eligibility check nor the query looks at the guest count, so somebody gets a search result they can't book (a room too small for their group), complains, and the team realizes the three rules disagree.

The Specification Pattern gives the rule a name and turns it into a small object, and the eligibility check, the query and the validation all use that object.

What the Specification Pattern is

A specification is a small object that answers one question: "does this thing satisfy this criterion?". Each kind of candidate gets its own interface here, so isSatisfiedBy() takes a real Room instead of any value. RoomSpecification also has three combinators, and(), or() and not(), which the next section implements:

PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\Room; interface RoomSpecification { public function isSatisfiedBy(Room $room): bool; public function and(RoomSpecification $other): RoomSpecification; public function or(RoomSpecification $other): RoomSpecification; public function not(): RoomSpecification; }

Concrete room specifications implement isSatisfiedBy(). They extend CompositeRoomSpecification, a small base class shown in the Composition section, which supplies the three combinators. Room here is built from an id, status, capacity and bookedStays (a list of DateRange), isAvailable() checks the status, and hasReservationOverlapping(DateRange) checks the booked stays. RoomId is the id value object from the capstone lesson. RoomStatus is a backed enum with an Available case, not shown. GuestCount is the value object from the Named Constructors lesson.

PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\Room; use App\Reservations\DateRange; final readonly class AvailableForStay extends CompositeRoomSpecification { public function __construct(public DateRange $stayDates) {} public function isSatisfiedBy(Room $room): bool { return $room->isAvailable() && !$room->hasReservationOverlapping($this->stayDates); } }
PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\GuestCount; use App\Booking\Room; final readonly class FitsGuestCount extends CompositeRoomSpecification { public function __construct(public GuestCount $guestCount) {} public function isSatisfiedBy(Room $room): bool { return $room->capacity >= $this->minimumCapacity(); } public function minimumCapacity(): int { return $this->guestCount->adults + $this->guestCount->children; } }

Reservations get their own interface. Nothing in this lesson combines reservation rules, so it has only isSatisfiedBy():

PHP
<?php declare(strict_types=1); namespace App\Reservations\Specifications; use App\Reservations\Reservation; interface ReservationSpecification { public function isSatisfiedBy(Reservation $reservation): bool; }

Reservation is trimmed to status, totalPrice, stayDates and cancellationPolicyType, read as public readonly properties (the Repository Pattern lesson reads the status through a status() method instead).

PHP
<?php declare(strict_types=1); namespace App\Reservations\Specifications; use App\Reservations\Cancellation\CancellationPolicyFactory; use App\Reservations\Reservation; use App\Reservations\ReservationStatus; use DateTimeImmutable; final readonly class RefundableReservation implements ReservationSpecification { public function __construct( private CancellationPolicyFactory $policies, private DateTimeImmutable $now, ) {} public function isSatisfiedBy(Reservation $reservation): bool { return $reservation->status === ReservationStatus::Confirmed && !$this->policies->for($reservation)->refundFor( $reservation->totalPrice, $reservation->stayDates, $this->now, )->isZero(); } }

ReservationStatus is the enum the Tell, Don't Ask lesson uses. RefundableReservation gets the policy from the factory in the Strategy Pattern lesson, so until the Null Object Pattern lesson adds the null arm, it throws UnhandledMatchError for a reservation with no policy type.

Composition

Specifications combine. The base class implements the three combinators once, so no concrete specification repeats them:

PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; abstract readonly class CompositeRoomSpecification implements RoomSpecification { public function and(RoomSpecification $other): RoomSpecification { return new RoomAndSpecification($this, $other); } public function or(RoomSpecification $other): RoomSpecification { return new RoomOrSpecification($this, $other); } public function not(): RoomSpecification { return new RoomNotSpecification($this); } }

The combinators are small specifications themselves. A RoomAndSpecification holds two other specifications, so a composed rule is a tree, and the plain specifications at its ends (AvailableForStay, FitsGuestCount) are its leaves:

PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\Room; final readonly class RoomAndSpecification extends CompositeRoomSpecification { public function __construct( public RoomSpecification $left, public RoomSpecification $right, ) {} public function isSatisfiedBy(Room $room): bool { return $this->left->isSatisfiedBy($room) && $this->right->isSatisfiedBy($room); } }
PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\Room; final readonly class RoomOrSpecification extends CompositeRoomSpecification { public function __construct( public RoomSpecification $left, public RoomSpecification $right, ) {} public function isSatisfiedBy(Room $room): bool { return $this->left->isSatisfiedBy($room) || $this->right->isSatisfiedBy($room); } }
PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\Room; final readonly class RoomNotSpecification extends CompositeRoomSpecification { public function __construct(public RoomSpecification $inner) {} public function isSatisfiedBy(Room $room): bool { return !$this->inner->isSatisfiedBy($room); } }

Build a compound rule in one class, so every caller gets the same rule:

PHP
<?php declare(strict_types=1); namespace App\Booking\Specifications; use App\Booking\GuestCount; use App\Reservations\DateRange; final class BookableForStay { public static function for(DateRange $stayDates, GuestCount $guestCount): RoomSpecification { return (new AvailableForStay($stayDates)) ->and(new FitsGuestCount($guestCount)); } }

The eligibility check and the booking validation both run the same one-line in-memory check: BookableForStay::for($stayDates, $guestCount)->isSatisfiedBy($room).

Specifications for queries

The same specification can also drive a database query through a repository. Rooms gets a matching() method that takes a specification:

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Booking\Specifications\RoomSpecification; interface Rooms { /** @return list<Room> */ public function matching(RoomSpecification $specification): array; }

The SQL for each leaf lives in a local scope on the Eloquent model. (ReservationModel is the model from the Repository Pattern lesson.)

PHP
<?php declare(strict_types=1); namespace App\Booking\Models; use App\Booking\RoomStatus; use App\Reservations\DateRange; use App\Reservations\Models\ReservationModel; use Illuminate\Database\Eloquent\Attributes\Scope; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; final class RoomModel extends Model { protected $table = 'rooms'; protected function casts(): array { return ['status' => RoomStatus::class]; } /** @return HasMany<ReservationModel, $this> */ public function reservations(): HasMany { return $this->hasMany(ReservationModel::class, 'room_id'); } #[Scope] protected function availableFor(Builder $query, DateRange $stayDates): void { $query->where('status', RoomStatus::Available->value) ->whereDoesntHave('reservations', fn (Builder $reservations) => $reservations ->where('check_in', '<', $stayDates->checkOut) ->where('check_out', '>', $stayDates->checkIn)); } #[Scope] protected function withCapacityOf(Builder $query, int $minimum): void { $query->where('capacity', '>=', $minimum); } }

The repository translates the specification by walking the tree: a RoomAndSpecification applies both sides, and each leaf calls its scope. match on the class name picks the arm, which works because every specification class is final. matching() then builds each Room from its row and parses the raw reservation dates itself, as the repository in the Repository Pattern lesson does:

PHP
<?php declare(strict_types=1); namespace App\Booking\Infrastructure; use App\Booking\Models\RoomModel; use App\Booking\Room; use App\Booking\RoomId; use App\Booking\Rooms; use App\Booking\Specifications\AvailableForStay; use App\Booking\Specifications\FitsGuestCount; use App\Booking\Specifications\RoomAndSpecification; use App\Booking\Specifications\RoomSpecification; use App\Reservations\DateRange; use App\Reservations\Models\ReservationModel; use Carbon\CarbonImmutable; use Illuminate\Database\Eloquent\Builder; use InvalidArgumentException; final readonly class EloquentRooms implements Rooms { public function matching(RoomSpecification $specification): array { $query = RoomModel::query()->with('reservations'); $this->apply($query, $specification); return array_map( fn (RoomModel $model): Room => new Room( id: new RoomId($model->id), status: $model->status, capacity: $model->capacity, bookedStays: $model->reservations ->map(fn (ReservationModel $reservation): DateRange => new DateRange( CarbonImmutable::parse($reservation->check_in), CarbonImmutable::parse($reservation->check_out), )) ->all(), ), $query->get()->all(), ); } /** @param Builder<RoomModel> $query */ private function apply(Builder $query, RoomSpecification $specification): void { match ($specification::class) { RoomAndSpecification::class => $this->applyBoth($query, $specification), AvailableForStay::class => $query->availableFor($specification->stayDates), FitsGuestCount::class => $query->withCapacityOf($specification->minimumCapacity()), default => throw new InvalidArgumentException( 'Cannot translate ' . $specification::class . ' to a query.', ), }; } /** @param Builder<RoomModel> $query */ private function applyBoth(Builder $query, RoomAndSpecification $specification): void { $this->apply($query, $specification->left); $this->apply($query, $specification->right); } }

The specification that BookableForStay::for() builds now answers "is this room bookable?" in memory and "which rooms are bookable?" as a query. The conditions themselves are written twice: AvailableForStay checks status and overlapping reservations in PHP, and the availableFor scope checks the same two things in the query. The pattern doesn't remove that second copy. It ties both copies to one class name, keeps the query copy in one scope, and makes drift testable: seed a few rooms, then assert that matching() returns exactly the rooms for which isSatisfiedBy() is true. RoomOrSpecification and RoomNotSpecification need their own arms in apply(), and a specification the repository can't translate throws instead of silently returning too many rooms.

A worked example

The product team says: "Show rooms that are available for the requested stay and fit the guest count."

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Booking\Specifications\BookableForStay; use App\Reservations\DateRange; final readonly class SearchRoomsHandler { public function __construct(private Rooms $rooms) {} /** @return list<Room> */ public function handle(DateRange $stayDates, GuestCount $guestCount): array { return $this->rooms->matching(BookableForStay::for($stayDates, $guestCount)); } }

If the rule changes (add "must be a Deluxe or Suite room type"), Room gains a type field and you write one new leaf, a RoomTypeIn specification that takes the allowed types, give it a whereIn scope and an arm in apply(), and add it to BookableForStay with Deluxe and Suite as the allowed types. The in-memory check, the search query and any UI eligibility check pick it up from there.

When specifications earn their place

The pattern earns its place when:

  • The same rule needs to be both checked and queried. Without specifications, the PHP check and the SQL query live in unrelated places under different names, and nobody notices when one changes without the other.

  • Rules combine often. "Available AND fits guest count AND fits budget" gets composed in many places. Specifications make composition cheap where named methods would multiply (availableForStayFittingGuestCountAtPropertyNotStayedAtRecently is the kind of method name that makes you wish for a different design).

  • Rules are domain concepts the business names. "Bookable for stay", "refundable reservation", "eligible for upgrade". When the business has a name for the rule, the rule wants to be a class.

  • Rules need to be tested in isolation. A specification with a single isSatisfiedBy method is trivial to test. The compound versions test their parts and then their composition.

It doesn't earn its place when:

  • The rule is used once. A match or a method on the entity is fine.

  • The rule is too tightly coupled to a specific query (joins, subqueries, complicated SQL) to translate cleanly. In those cases, a named repository method (Reservations::confirmedCheckInsTodayWithBalance()) is simpler than fighting to make the specification translatable.

  • The team isn't ready for the indirection. If the codebase isn't already using rich models and repositories, dropping specifications in alone is more confusing than helpful.

For a small Laravel app, I'd skip specifications. A handful of methods on the model (Room::isAvailableFor($stayDates), Room::fits($count)) and a handful of methods on the repository (Rooms::availableForDates()) are simpler. The balance between under-engineering and over-engineering applies: add the pattern once the rule is needed in both a check and a query.

Pitfalls

Specifications that can't be translated to queries. RefundableReservation is one: the refund comes from the cancellation policy's math in PHP, so no repository can turn it into a where clause without copying every policy's math into SQL. The pattern's main payoff (one rule for both check and query) breaks down. Recognize when a specification is in-memory-only and live with that limit, or refactor the rule until the persistence side can express it.

Building giant trees of specifications. A deeply nested tree of and/or/not specifications is hard to read. A few well-named compound specifications (BookableForStay, EligibleForUpgrade) give each subtree a name the business uses.

One family per candidate type. Typing the candidate has a cost: rooms need their own interface, base class and three combinator classes, and reservations would need the same set the day you combine reservation rules. PHP can't share one generic Specification interface and still type the parameter: if the interface takes object, a leaf that takes Room narrows the parameter, and PHP rejects that because an implementing method can widen a parameter type but never narrow it. Once the families multiply, one shared Specification with isSatisfiedBy(object $candidate) is less code: each leaf checks its type with instanceof, and PHPStan generics (@template T) check statically what PHP can't.

Mixing specification and query construction. Keep them apart: a specification should not have SQL in it, and the translator should only mirror what each specification checks, never add a condition of its own.

The one thing to remember

When you find yourself writing the same business rule in three places (the eligibility check, the query, the validation), the rule is asking to be a specification.

Course Content