State machines are no good if you cannot monitor their state to do something about it.
With State
, you can register transition listeners quite easily. Just attach a
callable to the transition
you want to monitor:
This will trigger the addPayment()
method on $order
whenever the pay
transition is
performed. The listener should have the following signature:
It accepts a $from
state, a $to
state and all
transition parameters you specified when calling the process()
method or
transition methods.
Sometimes you may want to monitor all transitions of a given state machine. This
is especially useful for logging purposes (e.g. keeping a state transition log
for orders of your e-commerce system). In this case, you can register a
global listener
by omitting the $transition
parameter to the on()
call:
The logging()
method of $order
will be called when any state transition happens
within the machine. It accepts the $transition
name, a $from
state, a $to
state, and an array of transition parameters.