Making Impossible States Unrepresentable: Finite State Machines & Event Sourcing in PHP 8.3

Kill boolean flag soup forever. Build a strict Finite State Machine, a zero-dependency SQLite Event Store, a CLI Time-Travel Debugger, and Read Projections in modern PHP 8.3
TL;DR: Storing workflow state across 6 boolean columns creates $2^6 = 64$ possible states when your business only allows 7. In this 3-part tutorial, we build the Galactic Parcel Service order engine in pure PHP 8.3—combining a Finite State Machine (backed enums + exhaustive
match), lightweight Event Sourcing (readonlyDTOs + SQLite), and an interactive Time-Travel CLI Debugger.
Companion Video Series & GitHub Repository
This written guide is the complete standalone reference for our 3-part video mini-series. Every code listing, diagram, benchmark, and retention quiz from the videos is included right here so you can watch along, read at your own pace, or keep this open as a desk reference.
php-fsm-event-sourcing repository
Follow Along with Progressive Git Branches
Clone the repository and switch branches as you move through each section:
| Tutorial Part | Git Branch | What You Will Build |
|---|---|---|
| Intro (The Bug) | 01-boolean-spaghetti | A classic CRUD Order class with 6 booleans and a test proving corrupted states slip through |
| Part 1 (FSM) | 02-enum-state-machine | Backed OrderStatus enum, exhaustive match rules, transition guards, and domain exceptions |
| Part 2 (Event Sourcing) | 03-event-sourced-aggregate | Immutable readonly Event DTOs, recordThat()/apply() aggregate, and an ACID SQLite Event Store |
| Part 3 (Time Travel) | 04-time-travel-cli-and-projections (main) | Temporal replay (reconstituteAt), interactive CLI Time Machine, and a retroactive Revenue Projection |
git clone https://github.com/your-username/php-fsm-event-sourcing.git cd php-fsm-event-sourcing composer install ./vendor/bin/phpunit Prerequisites: PHP 8.3+, Composer, basic OOP familiarity. No frameworks, no Kafka, and no prior Domain-Driven Design (DDD) experience required.
The Hook: Why Boolean Soup Ruins Your Friday at 4:55 PM
Picture this: it is Friday at 4:55 PM. You run Galactic Parcel Service—delivering freeze-dried ice cream and spare hyperdrives across the solar system. Suddenly, Finance pings you on Slack:
"Hey... why did we just issue a full refund for order
GPS-4042when it was cancelled yesterday, never paid for, AND is currently in transit to New Mars Colony?"
If you have worked on any mature PHP codebase, you already know the culprit. Open branch 01-boolean-spaghetti and look at our legacy Order class:
<?php declare(strict_types=1); final class LegacyOrder { public bool $isPaid = false; public bool $isPacked = false; public bool $isShipped = false; public bool $isDelivered = false; public bool $isCancelled = false; public bool $isRefunded = false; public function cancel(): void { $this->isCancelled = true; } public function ship(): void { // Oops: forgot to check !$this->isCancelled and $this->isPacked! $this->isShipped = true; } public function refund(): void { // Oops: forgot to check $this->isPaid and !$this->isShipped! $this->isRefunded = true; } } The Math Behind the Bug: The $2^n$ State Explosion
Six innocent-looking boolean columns do not represent 6 states. Because every boolean can be true or false independently, $n$ booleans generate $2^n$ distinct combinations:
$$\text{Total Representable States} = 2^n$$
For $n = 6$ booleans, our class can represent $2^6 = 64$ combinations—even though our actual order lifecycle only has 7 valid states. That means 57 out of 64 states (89.1%) are impossible garbage states waiting for a single forgotten if check.
xychart-beta title "The 2^n State Explosion: Total Representable States vs. Valid Lifecycle States" x-axis "Number of Boolean Flags (n)" [1, 2, 3, 4, 5, 6] y-axis "Number of States" 0 --> 70 bar [2, 4, 8, 16, 32, 64] line [2, 3, 4, 5, 6, 7] | Boolean Flags ($n$) | Total Combinations ($2^n$) | Valid Domain States | Impossible Garbage States | % Impossible |
|---|---|---|---|---|
| 1 | 2 | 2 | 0 | 0.0% |
| 2 | 4 | 3 | 1 | 25.0% |
| 3 | 8 | 4 | 4 | 50.0% |
| 4 | 16 | 5 | 11 | 68.8% |
| 5 | 32 | 6 | 26 | 81.3% |
| 6 | 64 | 7 | 57 | 89.1% |
Defensive if statements scattered across controllers and service classes cannot win against exponential growth. Instead, we need an architecture that makes impossible states unrepresentable.
Part 1: Modeling a Finite State Machine in Modern PHP
(Switch to branch 02-enum-state-machine to follow along with Video 1.)
A Finite State Machine (FSM) enforces three simple guarantees:
- Single Exclusive State: An order occupies exactly one state from a fixed, finite set at any instant.
- Explicit Allowed Transitions: Only declared edges between states are permitted; every unlisted edge is illegal by default.
- Transition Guards: Domain preconditions (like payment matching the order total, or a 30-day return window) must evaluate to
truebefore a valid edge can fire.
Visual 1: Galactic Parcel Service State Graph
stateDiagram-v2 classDef draft fill:#64748b,color:#fff,stroke:#475569 classDef paid fill:#0d9488,color:#fff,stroke:#0f766e classDef packed fill:#d97706,color:#fff,stroke:#b45309 classDef shipped fill:#4f46e5,color:#fff,stroke:#4338ca classDef delivered fill:#059669,color:#fff,stroke:#047857 classDef terminal fill:#dc2626,color:#fff,stroke:#b91c1c [*] --> Draft Draft --> Paid : PaymentCaptured Draft --> Cancelled : OrderCancelled Paid --> Packed : OrderPacked Paid --> Refunded : OrderRefunded Packed --> Shipped : OrderShipped Packed --> Refunded : OrderRefunded Shipped --> Delivered : OrderDelivered Delivered --> Refunded : OrderRefunded [<= 30 days] Cancelled --> [*] Refunded --> [*] class Draft draft class Paid paid class Packed packed class Shipped shipped class Delivered delivered class Cancelled,Refunded terminal Visual 2: The Complete State Transition Matrix
Every cell marked Illegal below is guaranteed to throw an InvalidStateTransitionException at runtime. Notice that once a parcel is Shipped, a direct refund is blocked—the parcel is hurtling through space and must reach Delivered first. Also note that Cancelled and Refunded are terminal states with zero outgoing transitions.
| Current State \ Action | capturePayment | pack | ship | deliver | cancel | refund |
|---|---|---|---|---|---|---|
Draft | $\rightarrow$ Paid | Illegal | Illegal | Illegal | $\rightarrow$ Cancelled | Illegal |
Paid | Illegal | $\rightarrow$ Packed | Illegal | Illegal | Illegal | $\rightarrow$ Refunded |
Packed | Illegal | Illegal | $\rightarrow$ Shipped | Illegal | Illegal | $\rightarrow$ Refunded |
Shipped | Illegal | Illegal | Illegal | $\rightarrow$ Delivered | Illegal | Illegal (In transit) |
Delivered | Illegal | Illegal | Illegal | Illegal | Illegal | $\rightarrow$ Refunded (Guard: $\le 30\text{d}$) |
Cancelled | Illegal | Illegal | Illegal | Illegal | Illegal | Illegal |
Refunded | Illegal | Illegal | Illegal | Illegal | Illegal | Illegal |
Step 1.1: The Backed Enum State Machine (OrderStatus.php)
PHP 8.1+ backed enums let us pair strict type safety with clean string persistence ('draft', 'paid', etc.). Even better, enums can hold methods—so the transition graph lives right alongside the states themselves:
<?php declare(strict_types=1); namespace GalacticParcel\Domain; enum OrderStatus: string { case Draft = 'draft'; case Paid = 'paid'; case Packed = 'packed'; case Shipped = 'shipped'; case Delivered = 'delivered'; case Cancelled = 'cancelled'; case Refunded = 'refunded'; /** * Returns every state directly reachable from the current state. * * Intentionally omits a `default` arm so adding a new enum case * without defining its transitions triggers an UnhandledMatchError * (and a static analysis error in PHPStan/Psalm). * * @return list<self> */ public function allowedTransitions(): array { return match ($this) { self::Draft => [self::Paid, self::Cancelled], self::Paid => [self::Packed, self::Refunded], self::Packed => [self::Shipped, self::Refunded], self::Shipped => [self::Delivered], self::Delivered => [self::Refunded], self::Cancelled => [], self::Refunded => [], }; } public function canTransitionTo(self $next): bool { return in_array($next, $this->allowedTransitions(), true); } public function isTerminal(): bool { return $this->allowedTransitions() === []; } } Pro Tip — Never add a
defaultarm to your FSMmatch: Unlikeswitch, PHP'smatchexpression is exhaustive. If a teammate addscase LostInSpace = 'lost_in_space';six months from now and forgets to wire its transitions, PHP throws an\UnhandledMatchErrorimmediately instead of silently returning an empty array.
Step 1.2: Expressive Domain Exceptions
When a transition fails, we want a crystal-clear diagnostic message rather than a generic RuntimeException:
<?php declare(strict_types=1); namespace GalacticParcel\Domain\Exception; use DomainException; use GalacticParcel\Domain\OrderStatus; final class InvalidStateTransitionException extends DomainException { public static function fromTransition( OrderStatus $from, OrderStatus $to, string $reason = '', ): self { $message = sprintf( 'Cannot transition order from "%s" to "%s".', $from->value, $to->value, ); if ($reason !== '') { $message .= ' Reason: ' . $reason; } return new self($message); } } Step 1.3: Enforcing Transitions & Guards Inside Order
Notice what is missing from Order below: there is no public function setStatus(OrderStatus $status) setter! External code can only express business intent through explicit domain methods (capturePayment(), pack(), ship(), deliver(), cancel(), refund()), all funneled through assertCanTransitionTo().
<?php declare(strict_types=1); namespace GalacticParcel\Domain; use DateTimeImmutable; use GalacticParcel\Domain\Exception\InvalidStateTransitionException; final class Order { private const int REFUND_WINDOW_DAYS = 30; private OrderStatus $status = OrderStatus::Draft; private ?string $warehouseId = null; private ?string $trackingCode = null; private ?DateTimeImmutable $deliveredAt = null; public function __construct( private readonly string $id, private readonly string $destination, private readonly int $totalCents, ) {} public function capturePayment(int $amountCents): void { $this->assertCanTransitionTo(OrderStatus::Paid); // Transition Guard: exact payment required if ($amountCents !== $this->totalCents) { throw InvalidStateTransitionException::fromTransition( $this->status, OrderStatus::Paid, sprintf('Expected %d cents, received %d cents.', $this->totalCents, $amountCents), ); } $this->status = OrderStatus::Paid; } public function pack(string $warehouseId): void { $this->assertCanTransitionTo(OrderStatus::Packed); $this->warehouseId = $warehouseId; $this->status = OrderStatus::Packed; } public function ship(string $trackingCode): void { $this->assertCanTransitionTo(OrderStatus::Shipped); $this->trackingCode = $trackingCode; $this->status = OrderStatus::Shipped; } public function deliver(DateTimeImmutable $deliveredAt): void { $this->assertCanTransitionTo(OrderStatus::Delivered); $this->deliveredAt = $deliveredAt; $this->status = OrderStatus::Delivered; } public function cancel(): void { $this->assertCanTransitionTo(OrderStatus::Cancelled); $this->status = OrderStatus::Cancelled; } public function refund(DateTimeImmutable $now): void { $this->assertCanTransitionTo(OrderStatus::Refunded); // Transition Guard: Delivered parcels must be within 30 days if ( $this->status === OrderStatus::Delivered && $this->deliveredAt !== null && $this->deliveredAt->modify('+' . self::REFUND_WINDOW_DAYS . ' days') < $now ) { throw InvalidStateTransitionException::fromTransition( $this->status, OrderStatus::Refunded, sprintf('Exceeded the %d-day post-delivery return window.', self::REFUND_WINDOW_DAYS), ); } $this->status = OrderStatus::Refunded; } private function assertCanTransitionTo(OrderStatus $next): void { if (!$this->status->canTransitionTo($next)) { throw InvalidStateTransitionException::fromTransition($this->status, $next); } } public function status(): OrderStatus { return $this->status; } } Official PHP Manual References (Part 1)
- PHP Manual: Enumerations (Backed Enums & Methods)
- PHP Manual:
matchExpression & Exhaustiveness - PHP Manual:
DomainExceptionSPL Class
Retention Quiz 1: Finite State Machines & Enums
Test your understanding of Part 1 before moving on! Click any spoiler to reveal the answer and explanation.
Question 1.1 (Multiple Choice): Based on our Galactic Parcel Service state machine, which sequence of method calls on a new Draft order will throw an InvalidStateTransitionException?
- A)
capturePayment()$\rightarrow$pack()$\rightarrow$refund() - B)
capturePayment()$\rightarrow$pack()$\rightarrow$ship()$\rightarrow$refund() - C)
capturePayment()$\rightarrow$refund() - D)
cancel()
Reveal Answer 1.1
Answer: B
Once an order enters Shipped, the parcel is in transit and cannot jump directly to Refunded; it must reach Delivered first. Options A, C, and D all follow legal edges in our State Transition Matrix.
Question 1.2 (True / False): In PHP, if you write a match ($status) expression covering an enum and omit the default arm, PHP will silently return null when it encounters an unhandled enum case.
Reveal Answer 1.2
Answer: False
Unlike switch, PHP's match expression is exhaustive. When no arm matches and there is no default arm, PHP throws an \UnhandledMatchError, turning missing workflow rules into immediate, loud errors.
Question 1.3 (Fill in the Blank): Complete the match arm inside OrderStatus::allowedTransitions() for a Paid order:
self::Paid => [self::______, self::______], Reveal Answer 1.3
Answer: Packed, Refunded (in either order)
After payment is captured, an order can move forward into warehouse fulfillment (Packed) or be reversed (Refunded). It cannot be Cancelled (which is reserved for unpaid Draft orders) or skip packing to become Shipped.
Part 2: Adding Memory with Lightweight Event Sourcing
(Switch to branch 03-event-sourced-aggregate to follow along with Video 2.)
Our state machine guarantees valid transitions, yet our application still suffers from CRUD Amnesia.
If you inspect a traditional orders table tomorrow and see status = 'refunded', you have no idea how it got there. Was it refunded immediately after payment? After being packed at ORBITAL-HUB-7? Or 14 days after delivery? Every SQL UPDATE statement overwrites and destroys the past.
Event Sourcing flips persistence upside down: instead of saving only the mutable latest state, we persist the immutable, append-only sequence of Domain Events that happened to the order.
Visual 3: Destructive UPDATE vs. Append-Only Event Ledger
flowchart LR subgraph CRUD["Traditional CRUD (Destructive UPDATE)"] direction TB U1["status = 'draft'"] -->|"OVERWRITTEN"| U2["status = 'paid'"] U2 -->|"OVERWRITTEN"| U3["status = 'packed'"] U3 -->|"OVERWRITTEN"| U4["status = 'refunded'<br/>(History lost!)"] end subgraph ES["Event Sourcing (Append-Only Ledger)"] direction TB E1["v1: OrderCreated (10:00)"] E2["v2: PaymentCaptured (10:02)"] E3["v3: OrderPacked (10:15)"] E4["v4: OrderRefunded (10:40)"] E1 --- E2 --- E3 --- E4 end The Mental Model: Decide, Record, Apply
Mathematically, an entity's current state $\text{State}_n$ is simply a left-fold of an initial state $\text{State}_0$ over its ordered event stream $E_1, E_2, \dots, E_n$:
$$\text{State}_n = \text{apply}\Big(\dots \text{apply}\big(\text{apply}(\text{State}_0, E_1), E_2\big) \dots, E_n\Big)$$
Inside our Order Aggregate Root, we strictly separate deciding from applying:
sequenceDiagram participant Caller participant Order as Order Aggregate participant FSM as OrderStatus FSM participant Store as SqliteEventStore Caller->>Order: ship("WARP-9942", $now) Order->>FSM: canTransitionTo(Shipped)? alt Illegal Transition FSM-->>Order: false Order-->>Caller: throw InvalidStateTransitionException else Valid Transition FSM-->>Order: true Order->>Order: recordThat(new OrderShipped(...)) Note right of Order: 1. Push to $recordedEvents<br/>2. Call pure apply($event) Caller->>Order: releaseEvents() Order-->>Caller: [OrderShipped] Caller->>Store: append("GPS-4042", $events, $expectedVersion) Store-->>Caller: Committed (version = 4) end The Golden Rule of
apply(): Yourapply()method must be 100% pure and side-effect free. Never send emails, call payment gateways, or readnew DateTimeImmutable('now')insideapply(), becauseapply()executes every time you reload an order from the database!
Step 2.1: Immutable readonly Event DTOs
Events represent historical facts—you cannot rewrite history. Declaring every event class as readonly enforces immutability at the PHP engine level.
First, our DomainEvent contract (src/Domain/Event/DomainEvent.php):
<?php declare(strict_types=1); namespace GalacticParcel\Domain\Event; use DateTimeImmutable; interface DomainEvent { public function aggregateId(): string; public function occurredAt(): DateTimeImmutable; public function eventName(): string; /** @return array<string, mixed> */ public function toPayload(): array; /** @param array<string, mixed> $payload */ public static function fromPayload( string $aggregateId, array $payload, DateTimeImmutable $occurredAt, ): self; } Next, here is OrderShipped.php (all 7 domain events follow this exact concise readonly blueprint):
<?php declare(strict_types=1); namespace GalacticParcel\Domain\Event; use DateTimeImmutable; final readonly class OrderShipped implements DomainEvent { public function __construct( public string $orderId, public string $trackingCode, public DateTimeImmutable $occurredAt, ) {} public function aggregateId(): string { return $this->orderId; } public function occurredAt(): DateTimeImmutable { return $this->occurredAt; } public function eventName(): string { return 'order.shipped'; } public function toPayload(): array { return [ 'tracking_code' => $this->trackingCode, ]; } public static function fromPayload( string $aggregateId, array $payload, DateTimeImmutable $occurredAt, ): self { return new self( orderId: $aggregateId, trackingCode: (string) $payload['tracking_code'], occurredAt: $occurredAt, ); } } Catalog of All 7 Domain Events
| Event Class | eventName() | Key Payload Fields | Target OrderStatus |
|---|---|---|---|
OrderCreated | order.created | destination, total_cents | Draft |
PaymentCaptured | payment.captured | amount_cents | Paid |
OrderPacked | order.packed | warehouse_id | Packed |
OrderShipped | order.shipped | tracking_code | Shipped |
OrderDelivered | order.delivered | (timestamp in occurred_at) | Delivered |
OrderCancelled | order.cancelled | reason | Cancelled |
OrderRefunded | order.refunded |