Lesson 33 of 45 · Persistence, Flow and State
The State Pattern
Five methods, one question
The Strategy pattern lesson left a pointer: a reservation that behaves differently as ReservationStatus::Pending, Confirmed or CheckedIn is a State problem. Here is what that looks like in code. The plain Reservation from the earlier lessons is trimmed here to the status and the five methods that depend on it. The three later methods take the current time, as the existing handlers already call them, and check-in and no-show refuse to run before the arrival date. cancel() returns void as in the command-query separation lesson: a handler asks for the refund first, then cancels. The recorded events (ReservationCancelled, GuestCheckedOut), paymentId() and the PaymentAuthorization that confirm() takes are left out of the sketch.
The statuses are Pending, Confirmed, CheckedIn, CheckedOut, Cancelled and NoShow. The earlier lessons only let a Confirmed reservation be cancelled before check-in. This lesson also lets a Pending reservation be cancelled, with no refund because it was never paid. Each method asks the same question, "is the reservation in a status where this is allowed?", and answers it with its own if:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Reservations\Exceptions\CannotCancelReservation;
use App\Reservations\Exceptions\CannotChangeReservationStatus;
use App\Reservations\Exceptions\CannotConfirmReservation;
use DateTimeImmutable;
final class Reservation
{
public function __construct(
public readonly ReservationId $id,
private ReservationStatus $status,
private DateRange $stayDates,
private Money $totalPrice,
private ?DateTimeImmutable $cancelledAt = null,
private ?string $cancellationReason = null,
private ?DateTimeImmutable $checkedOutAt = null,
) {}
public function confirm(): void
{
if ($this->status !== ReservationStatus::Pending) {
throw new CannotConfirmReservation($this->id, $this->status);
}
$this->status = ReservationStatus::Confirmed;
}
public function cancel(string $reason, DateTimeImmutable $now): void
{
$cancellable = $this->status === ReservationStatus::Pending
|| $this->status === ReservationStatus::Confirmed;
if (!$cancellable || $this->stayDates->checkIn <= $now) {
throw new CannotCancelReservation($this->id);
}
$this->status = ReservationStatus::Cancelled;
$this->cancelledAt = $now;
$this->cancellationReason = $reason;
}
public function checkIn(DateTimeImmutable $now): void
{
if ($this->status !== ReservationStatus::Confirmed || $now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'check in');
}
$this->status = ReservationStatus::CheckedIn;
}
public function checkOut(DateTimeImmutable $now): void
{
if ($this->status !== ReservationStatus::CheckedIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'check out');
}
$this->status = ReservationStatus::CheckedOut;
$this->checkedOutAt = $now;
}
public function markNoShow(DateTimeImmutable $now): void
{
if ($this->status !== ReservationStatus::Confirmed || $now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'mark as no-show');
}
$this->status = ReservationStatus::NoShow;
}
}CannotConfirmReservation and CannotCancelReservation are the exceptions from the earlier lessons. CannotChangeReservationStatus is a new one with the same shape as ReservationNotConfirmed from the Exception Handling as Design lesson, taking the id, the current status and a verb. None of the three is shown.
Nothing here is wrong, but the cost shows up when a status is added. Suppose the hotel adds Expired for pending reservations nobody paid for. You have to find every method, decide what Expired means for each, and nothing tells you which ones you missed. The rules about which status allows which action are spread over five if statements, so nobody can read the lifecycle in one place.
Step one: a transition table on the enum
Before reaching for classes, collect the rules in one place. A PHP enum can have methods, and ReservationStatus is the natural home for "where can I go from here":
<?php
declare(strict_types=1);
namespace App\Reservations;
enum ReservationStatus: string
{
case Pending = 'pending';
case Confirmed = 'confirmed';
case CheckedIn = 'checked_in';
case CheckedOut = 'checked_out';
case Cancelled = 'cancelled';
case NoShow = 'no_show';
public function canTransitionTo(self $next): bool
{
return match ($this) {
self::Pending => in_array($next, [self::Confirmed, self::Cancelled], true),
self::Confirmed => in_array($next, [self::CheckedIn, self::Cancelled, self::NoShow], true),
self::CheckedIn => $next === self::CheckedOut,
self::CheckedOut, self::Cancelled, self::NoShow => false,
};
}
}The match has no default arm, so PHP throws UnhandledMatchError if you add Expired and forget to say where it goes. The whole lifecycle now reads top to bottom in one method. A fixed set of states plus the list of moves allowed between them is called a state machine, and this enum is one. The State pattern later in this lesson is another way to write a state machine, for when each state also behaves differently. Reservation shrinks to one private method that every action goes through:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Reservations\Exceptions\CannotCancelReservation;
use App\Reservations\Exceptions\CannotChangeReservationStatus;
use DateTimeImmutable;
final class Reservation
{
public function __construct(
public readonly ReservationId $id,
private ReservationStatus $status,
private DateRange $stayDates,
private Money $totalPrice,
private ?DateTimeImmutable $cancelledAt = null,
private ?string $cancellationReason = null,
private ?DateTimeImmutable $checkedOutAt = null,
) {}
public function confirm(): void
{
$this->moveTo(ReservationStatus::Confirmed, 'confirm');
}
public function cancel(string $reason, DateTimeImmutable $now): void
{
if ($this->stayDates->checkIn <= $now) {
throw new CannotCancelReservation($this->id);
}
$this->moveTo(ReservationStatus::Cancelled, 'cancel');
$this->cancelledAt = $now;
$this->cancellationReason = $reason;
}
public function checkIn(DateTimeImmutable $now): void
{
if ($now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'check in before arrival');
}
$this->moveTo(ReservationStatus::CheckedIn, 'check in');
}
public function checkOut(DateTimeImmutable $now): void
{
$this->moveTo(ReservationStatus::CheckedOut, 'check out');
$this->checkedOutAt = $now;
}
public function markNoShow(DateTimeImmutable $now): void
{
if ($now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'mark as no-show before arrival');
}
$this->moveTo(ReservationStatus::NoShow, 'mark as no-show');
}
private function moveTo(ReservationStatus $next, string $action): void
{
if (!$this->status->canTransitionTo($next)) {
throw new CannotChangeReservationStatus($this->id, $this->status, $action);
}
$this->status = $next;
}
}The table replaced five scattered if statements, and CannotChangeReservationStatus now covers every refusal except a late cancel, which still throws CannotCancelReservation. That changes what callers catch: confirm() and cancel() from the wrong status used to throw CannotConfirmReservation and CannotCancelReservation, and now throw CannotChangeReservationStatus. Often this is the right place to stop. The enum answers "is this move allowed?", and every action still does the same small thing: change the status. The next step only pays when that stops being true.
When the enum stops being enough
The table says which moves are legal. It cannot say that the moves do different things. Say each status starts to carry behavior of its own. The refund is the clearest case:
A
Pendingreservation has not been charged, so cancelling it refunds nothing.A
Confirmedreservation has been charged, so the refund comes from the cancellation policy from the Strategy pattern lesson.A reservation that cannot be cancelled has no refund to ask about.
Now the refund question needs a match on the status inside Reservation, and every new status touches that method. That is the point where the Gang of Four's State pattern earns its place. SourceMaking states the intent as: "Allow an object to alter its behavior when its internal state changes. The object will appear to change its class." The mechanism is that each status becomes a class, and the reservation hands each action to the class for its current status.
Step two: one class per status
Start with the interface. Each action returns the state the reservation moves into, so a state never has to reach back into Reservation to change it. refundFor() is a query. It changes nothing and returns Money, so it sits beside the actions without breaking command-query separation:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\DateRange;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
use DateTimeImmutable;
interface ReservationState
{
public function status(): ReservationStatus;
public function refundFor(
ReservationId $id,
Money $totalPrice,
DateRange $stayDates,
DateTimeImmutable $now,
CancellationPolicy $policy,
): Money;
public function confirm(ReservationId $id): ReservationState;
public function cancel(ReservationId $id): ReservationState;
public function checkIn(ReservationId $id): ReservationState;
public function checkOut(ReservationId $id): ReservationState;
public function markNoShow(ReservationId $id): ReservationState;
}Most statuses refuse most actions. Writing five throwing methods in six classes is the boilerplate that makes people give up on State, so an abstract base class refuses everything by default:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\DateRange;
use App\Reservations\Exceptions\CannotCancelReservation;
use App\Reservations\Exceptions\CannotChangeReservationStatus;
use App\Reservations\Exceptions\CannotConfirmReservation;
use App\Reservations\ReservationId;
use DateTimeImmutable;
abstract class RefusesEverything implements ReservationState
{
public function refundFor(
ReservationId $id,
Money $totalPrice,
DateRange $stayDates,
DateTimeImmutable $now,
CancellationPolicy $policy,
): Money {
throw new CannotCancelReservation($id);
}
public function confirm(ReservationId $id): ReservationState
{
throw new CannotConfirmReservation($id, $this->status());
}
public function cancel(ReservationId $id): ReservationState
{
throw new CannotCancelReservation($id);
}
public function checkIn(ReservationId $id): ReservationState
{
throw new CannotChangeReservationStatus($id, $this->status(), 'check in');
}
public function checkOut(ReservationId $id): ReservationState
{
throw new CannotChangeReservationStatus($id, $this->status(), 'check out');
}
public function markNoShow(ReservationId $id): ReservationState
{
throw new CannotChangeReservationStatus($id, $this->status(), 'mark as no-show');
}
}Each live status overrides only what it allows. Pending can be confirmed or cancelled:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\DateRange;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
use DateTimeImmutable;
final class Pending extends RefusesEverything
{
public function status(): ReservationStatus
{
return ReservationStatus::Pending;
}
public function refundFor(
ReservationId $id,
Money $totalPrice,
DateRange $stayDates,
DateTimeImmutable $now,
CancellationPolicy $policy,
): Money {
return Money::zero($totalPrice->currency);
}
public function confirm(ReservationId $id): ReservationState
{
return new Confirmed();
}
public function cancel(ReservationId $id): ReservationState
{
return new Closed(ReservationStatus::Cancelled);
}
}Confirmed can be cancelled, checked in, or marked as a no-show:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\DateRange;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
use DateTimeImmutable;
final class Confirmed extends RefusesEverything
{
public function status(): ReservationStatus
{
return ReservationStatus::Confirmed;
}
public function refundFor(
ReservationId $id,
Money $totalPrice,
DateRange $stayDates,
DateTimeImmutable $now,
CancellationPolicy $policy,
): Money {
return $policy->refundFor($totalPrice, $stayDates, $now);
}
public function cancel(ReservationId $id): ReservationState
{
return new Closed(ReservationStatus::Cancelled);
}
public function checkIn(ReservationId $id): ReservationState
{
return new CheckedIn();
}
public function markNoShow(ReservationId $id): ReservationState
{
return new Closed(ReservationStatus::NoShow);
}
}CheckedIn can only be checked out:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
final class CheckedIn extends RefusesEverything
{
public function status(): ReservationStatus
{
return ReservationStatus::CheckedIn;
}
public function checkOut(ReservationId $id): ReservationState
{
return new Closed(ReservationStatus::CheckedOut);
}
}CheckedOut, Cancelled and NoShow have the same behavior: nothing is allowed. One class carries the status it stands for, instead of three empty classes:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Reservations\ReservationStatus;
final class Closed extends RefusesEverything
{
public function __construct(private readonly ReservationStatus $status) {}
public function status(): ReservationStatus
{
return $this->status;
}
}The reservation still stores only its status. It builds the state object for the current status when an action runs, delegates to it, and keeps the status of the state it gets back:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Reservations\Exceptions\CannotCancelReservation;
use App\Reservations\Exceptions\CannotChangeReservationStatus;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\State\ReservationState;
use App\Reservations\State\ReservationStates;
use DateTimeImmutable;
final class Reservation
{
public function __construct(
public readonly ReservationId $id,
private ReservationStatus $status,
private DateRange $stayDates,
private Money $totalPrice,
private ?DateTimeImmutable $cancelledAt = null,
private ?string $cancellationReason = null,
private ?DateTimeImmutable $checkedOutAt = null,
) {}
public function status(): ReservationStatus
{
return $this->status;
}
public function refundFor(DateTimeImmutable $now, CancellationPolicy $policy): Money
{
return $this->state()->refundFor($this->id, $this->totalPrice, $this->stayDates, $now, $policy);
}
public function confirm(): void
{
$this->moveTo($this->state()->confirm($this->id));
}
public function cancel(string $reason, DateTimeImmutable $now): void
{
if ($this->stayDates->checkIn <= $now) {
throw new CannotCancelReservation($this->id);
}
$this->moveTo($this->state()->cancel($this->id));
$this->cancelledAt = $now;
$this->cancellationReason = $reason;
}
public function checkIn(DateTimeImmutable $now): void
{
if ($now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'check in before arrival');
}
$this->moveTo($this->state()->checkIn($this->id));
}
public function checkOut(DateTimeImmutable $now): void
{
$this->moveTo($this->state()->checkOut($this->id));
$this->checkedOutAt = $now;
}
public function markNoShow(DateTimeImmutable $now): void
{
if ($now < $this->stayDates->checkIn) {
throw new CannotChangeReservationStatus($this->id, $this->status, 'mark as no-show before arrival');
}
$this->moveTo($this->state()->markNoShow($this->id));
}
private function state(): ReservationState
{
return ReservationStates::for($this->status);
}
private function moveTo(ReservationState $next): void
{
$this->status = $next->status();
}
}A handler asks $reservation->refundFor($now, $policy) first and then calls cancel(). The handler below is the ask-before-telling version from the command-query separation lesson with the isZero() guard. Only the refund line changed. paymentId() is on the full class and trimmed from this sketch:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Payments\Payments;
use App\Reservations\Cancellation\CancellationPolicy;
use Psr\Clock\ClockInterface;
final readonly class CancelReservationCommandHandler
{
public function __construct(
private Reservations $reservations,
private CancellationPolicy $policy,
private Payments $payments,
private ClockInterface $clock,
) {}
public function handle(CancelReservationCommand $command): void
{
$now = $this->clock->now();
$reservation = $this->reservations->withId($command->reservationId);
$refund = $reservation->refundFor($now, $this->policy);
$reservation->cancel($command->reason, $now);
$this->reservations->save($reservation);
if (!$refund->isZero()) {
$this->payments->refund($reservation->paymentId(), $refund);
}
}
}Pending answers zero without consulting the policy, Confirmed asks it, and a CheckedIn reservation throws CannotCancelReservation from the base class. That is behavior that differs by status, which a transition table cannot hold.
The rule about arrival day stays on Reservation because it depends on dates, not on the status.
Adding Expired now means one new class, one line in the factory below, and an override in Pending for the move into it. No existing method on Reservation changes.
Persisting a state object
The database column still holds the enum value, 'confirmed', not a serialized object. The factory that rebuilds the state from the enum lives in one place:
<?php
declare(strict_types=1);
namespace App\Reservations\State;
use App\Reservations\ReservationStatus;
final class ReservationStates
{
public static function for(ReservationStatus $status): ReservationState
{
return match ($status) {
ReservationStatus::Pending => new Pending(),
ReservationStatus::Confirmed => new Confirmed(),
ReservationStatus::CheckedIn => new CheckedIn(),
ReservationStatus::CheckedOut,
ReservationStatus::Cancelled,
ReservationStatus::NoShow => new Closed($status),
};
}
}Reservation::state() calls it on every action. The status column and the status() accessor are unchanged, so the state objects need nothing from persistence, and the repository still writes $reservation->status()->value when it saves. Besides the status, this sketch keeps only stayDates and totalPrice, so its repository maps those two plus new columns for cancelledAt, cancellationReason and checkedOutAt. The full class maps the rest as in the repository lesson. Building the state on demand also matters for Doctrine, which loads an entity without calling its constructor: a state object set only in the constructor would be missing after every load. Doctrine maps the status property as an enum column and never sees a state object, because the state is derived, not stored. The state objects hold no data of their own, which is also why the Closed constructor argument is safe to rebuild from the column.
Checking that it behaves
The refusals and the refund are the parts worth testing, because they are the rules. A confirmed reservation can be checked in once and a second check-in is refused, and only a confirmed reservation asks the policy for a refund:
<?php
declare(strict_types=1);
namespace Tests\Unit\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use App\Reservations\DateRange;
use App\Reservations\Exceptions\CannotChangeReservationStatus;
use App\Reservations\Reservation;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
final class ReservationStateTest extends TestCase
{
public function test_a_checked_in_reservation_cannot_be_checked_in_again(): void
{
$reservation = $this->reservationIn(ReservationStatus::Confirmed);
$now = CarbonImmutable::parse('2026-12-01 15:00');
$reservation->checkIn($now);
$this->assertSame(ReservationStatus::CheckedIn, $reservation->status());
$this->expectException(CannotChangeReservationStatus::class);
$reservation->checkIn($now);
}
public function test_only_a_confirmed_reservation_asks_the_policy(): void
{
$refundEverything = new class implements CancellationPolicy {
public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money
{
return $totalPrice;
}
};
$now = CarbonImmutable::parse('2026-11-20');
$pending = $this->reservationIn(ReservationStatus::Pending);
$confirmed = $this->reservationIn(ReservationStatus::Confirmed);
$this->assertSame(0, $pending->refundFor($now, $refundEverything)->amountInCents);
$this->assertSame(42000, $confirmed->refundFor($now, $refundEverything)->amountInCents);
}
private function reservationIn(ReservationStatus $status): Reservation
{
return new Reservation(
id: ReservationId::next(),
status: $status,
stayDates: new DateRange(
CarbonImmutable::parse('2026-12-01'),
CarbonImmutable::parse('2026-12-04'),
),
totalPrice: Money::fromCents(42000, Currency::usd()),
);
}
}The check-in test uses only public methods, so it passes against the enum version too once that version has the same status() accessor. The refund test needs refundFor(), which only the state version has.
State vs Strategy
The two patterns have the same shape: an interface, several implementations, and a context that delegates. They differ in who decides which implementation is in use.
Strategy: the caller or the container picks.
CancellationPolicyis chosen from the reservation's policy type, and nothing the policy does changes which policy is selected.State: the object picks, and does it by running.
Confirmed::checkIn()returnsCheckedIn, so the next action goes to a different class because the last action happened.
Pitfalls
Giving each state the whole entity. The classic GoF shape passes the context into the state, and the state calls a setter on it. That forces Reservation to expose a way to change its status, and any service can then call it and skip the rules, the problem the rich domain model lesson described for setters. Returning the next state keeps the setter private.
Too many transitions for classes. Each live status here overrides one to four action methods. When most states override most methods, the classes are a transition table in a worse format. Go back to the enum.
Putting date and money rules in the states. A rule that applies in every status, such as "no cancelling after arrival", belongs on Reservation. Duplicating it in Pending and Confirmed is how two copies drift.
The one thing to remember
When every method on a class starts by checking its status, first collect the allowed moves in an enum with a transition table. Move to one class per status only when the statuses start doing different work, and keep the rules that don't depend on status on the entity.