Best Practices
Designing a state machine is different from writing procedural code. In a statechart, you model conditions and transitions rather than step-by-step instructions. These best practice guides distil lessons learned from real-world EventMachine projects into focused, actionable advice.
Quick Reference
| Topic | One-Liner |
|---|---|
| Naming & Style | Consistent naming for states, events, behaviors, and context |
| State Design | Model conditions, not steps; avoid state explosion |
| Event Design | Events are past-tense facts, not commands |
| Transition Design | Self vs targetless, @always chains, multi-branch |
| Guard Design | Guards must be pure -- no side effects, no I/O |
| Action Design | Idempotency, entry vs transition vs exit |
| Context Design | Lean context; flags that change transitions belong in states |
| Event Bubbling | Understand leaf-to-root handler resolution |
| Machine Decomposition | When to split, when to keep together |
| Sync Child Machines | Default-mode delegation, idle + @always bootstrap, output in parallel regions |
| Machine System Design | Communication patterns, hierarchy, timer placement |
| Time-Based Patterns | after, every, escalation, idempotency |
| Parallel Patterns | Region independence, context separation, @done |
| Testing Strategy | Four layers: unit, integration, E2E, LocalQA |
How to Read These Guides
Each page follows the same structure:
- Core principle -- the one rule that matters most
- Do / Don't examples -- always with code
- Refactoring recipe -- turning an anti-pattern into a clean design
- Cross-references -- links to the relevant reference documentation
The tone is practical. "Generally" means "in most projects we have seen". If your domain calls for something different, trust your domain -- but understand the trade-off.
Background Reading
EventMachine's design draws heavily from statechart theory and existing implementations:
- David Harel, "Statecharts: A Visual Formalism for Complex Systems" (1987) -- the foundational paper introducing hierarchical and parallel states.
- W3C SCXML Specification -- the XML-based statechart standard that formalises event processing, transition selection, and document order.
- XState (Stately) -- the JavaScript statechart library that popularised statecharts in modern application development. EventMachine follows many of the same semantics while using its own PHP-native API.
- UML State Machine Diagrams -- the OMG standard for modelling reactive systems with states, transitions, and regions.
Understanding these foundations helps you reason about why EventMachine works the way it does, not just how.