Skip to content

Lesson 2 of 9 · 21m

Enums, readonly, and Value Objects That Stay Valid

Replace class constants and mutable bags of state with backed enums, readonly objects, and small domain values that enforce themselves.

Legacy PHP represented domain concepts with strings and hope: 'active', 'enabled', 'A', sometimes 1. Half the bug reports in old systems are vocabulary bugs — an invalid state that should never have existed outside a database CHECK constraint. PHP 8.1 enums and 8.2 readonly classes finally let the language carry invariants that used to live only in code review comments.

Enums are finite sets, not constants with better marketing

enum InvoiceStatus: string
{
    case Draft = 'draft';
    case Issued = 'issued';
    case Paid = 'paid';
    case Void = 'void';

    public function canTransitionTo(self $next): bool
    {
        return match (true) {
            $this === self::Draft && $next === self::Issued,
            $this === self::Issued && in_array($next, [self::Paid, self::Void], true) => true,
            default => false,
        };
    }
}

A backed enum maps directly to storage. A pure enum has no scalar value and is useful when persistence should be an explicit mapping. Both are singletons: identity comparison with === is correct, and you cannot instantiate them with new.

Readonly removes the “who mutated this?” mystery

final readonly class Money
{
    public function __construct(
        public int $cents,
        public string $currency,
    ) {
        if ($cents < 0) {
            throw new InvalidArgumentException('Money cannot be negative');
        }
    }
}

A readonly object cannot be modified after construction. That does not make nested objects deeply immutable — a readonly property containing a mutable object still contains a mutable object — but it eliminates the worst category of PHP bug: a service quietly changing a value object after it was passed to three other services.

Value objects beat associative arrays

['amount' => 1200, 'currency' => 'USD'] tells the reader nothing about whether keys exist, which types they hold, or whether someone added amount_cents in one module and cents in another. A value object is more typing today and less debugging every day after.

function price(Invoice $invoice): Money
{
    return new Money($invoice->subtotalCents() + $invoice->taxCents(), 'USD');
}

Use enums for transitions, not just labels

The high-value move is putting state-transition rules beside the enum. Invalid transitions become impossible to express instead of merely unlikely. If a workflow has hundreds of transitions, use a dedicated state machine, but for most CRUD-adjacent systems an enum method is the correct amount of machinery.

Field notes

  • Enum cases are not strings. Persist $status->value; rehydrate with InvoiceStatus::from($stored) or tryFrom when corrupt legacy rows are possible.
  • from() throws ValueError on unknown backing values. Treat that as data corruption, not user input.
  • readonly properties cannot have static type static, cannot be redeclared writable by children, and readonly classes cannot declare static properties.
  • Do not make every object readonly. Entities with lifecycle state are mutable by design; values and events are the good candidates.
  • Enums can implement interfaces and use traits, but cannot extend classes because they already have a fixed internal representation.

Was this lesson helpful?

Sign in to rate