A lightweight, zero-dependency Finite State Machine (FSM) builder for HolyPHP with named states, transitions, transition history, and onEnter / onExit lifecycle hooks.
bundled — works offlinezero dependenciesstatemachine
Defines a transition from state $from to state $to triggered by $event. Automatically registers $from and $to if not already registered. Returns $this for chaining.
onEnter(string $state, $callback): StateMachine
Registers a callback function($from, $to, $event, $payload) invoked whenever the machine enters $state. Returns $this for chaining.
onExit(string $state, $callback): StateMachine
Registers a callback function($from, $to, $event, $payload) invoked whenever the machine exits $state. Returns $this for chaining.
can(string $event): bool
Returns true if $event is a valid transition from the current state, false otherwise.
availableEvents(): array
Returns an array of event names that can currently be triggered from the current state.
transitionsFrom(string $state): array
Returns a map of event => targetState for the given registered state.
trigger(string $event, $payload = null): string
Executes the transition for $event from the current state:
Invokes all onExit hooks for the current state.
Updates the current state to the target state.
Appends ["from" => $from, "to" => $to, "event" => $event, "payload" => $payload] to the history log.
Invokes all onEnter hooks for the target state.
Returns the new state name.
state(): string
Returns the current state name.
is(string $state): bool
Returns true if the current state equals $state.
history(): array
Returns the ordered array of transition records performed since creation or the last reset().
reset(): StateMachine
Resets the current state back to the initial state and clears the transition history. Returns $this for chaining.
Error Handling
All invalid operations throw an Exception with a clear fsm: prefixed message:
Empty initial state: fsm: initial state must be a non-empty string
Empty state/event name: fsm: state name must be a non-empty string, fsm: event name must be a non-empty string, fsm: source state must be a non-empty string, fsm: target state must be a non-empty string
Unknown state in onEnter, onExit, or transitionsFrom: fsm: unknown state '<state>'
Invalid transition in trigger: fsm: invalid transition on event '<event>' from state '<state>'
Examples
01Quick start
Bundled with the compiler — import "fsm"; works offline in any file, or add it to a project with hphp install fsm.