Model immutable domain types with PHP enums and readonly

8 steps · about 2 h 5 min · Intermediate

  1. PHP enumerations overview (reference, PHP Manual, 15 min)

    See how PHP 8.1+ enums replace ad-hoc class constants with closed, type-checked case sets.

  2. Basic (pure) enumerations (reference, PHP Manual, 15 min)

    Define pure enum cases and compare them by identity without accidental scalar coercion.

  3. Backed enumerations (from and tryFrom) (reference, PHP Manual, 20 min)

    Map database strings and API payloads safely onto typed enum cases with tryFrom().

  4. Adding methods and interfaces to PHP enums (reference, PHP Manual, 15 min)

    Keep state-specific behaviour on the enum itself instead of scattering switch blocks across callers.

  5. Differences between enums and regular objects (reference, PHP Manual, 15 min)

    Learn why enums disallow state, cloning and constructors so singleton case guarantees hold.

  6. Strict, exhaustive match expressions (reference, PHP Manual, 20 min)

    Pair enums with match() for identity comparisons, return values and UnhandledMatchError safety.

  7. Controlling inheritance with final classes and methods (reference, PHP Manual, 10 min)

    Lock down value-object invariants so subclasses cannot silently reintroduce mutability.

  8. Object cloning and immutable with-style updates (reference, PHP Manual, 15 min)

    Understand __clone semantics in PHP 8.2+ readonly classes when deriving modified value-object copies.