Download the PHP package byjg/statemachine without Composer
On this page you can find all versions of the php package byjg/statemachine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package statemachine
State Machine
This component implements a Finite State Machine, which can define several states and group them in a collection of transitions (from one state to another state). In addition, each state can have a conditional allowing move to another state.
Differently from other State machines, this implementation doesn't have an initial or final state.
Basic Example
Let's use the following example.
We have the states A, B, C, and D, and it's their possible transitions.
First, we create the states:
Then, we define the transitions. Note that each transition object can have a closure
that receives a mixed type data
. This closure needs to return true
or false
,
allowing or not the transition.
After creating the states and the transition, we can create the State Machine:
We can validate the transition using the method canTransition($from, $to)
. Some examples:
We can also check if a state is initial or final:
Other ways to create the State Machine
Alternatively, you can create the state machine using the createMachine
factory method with arguments as follows:
Using the Auto Transition
Another feature of this component is that depending on the state you are in and the data you pass to the state machine, it can decide what is the next state you can be.
Let's analyze the following states.
The transition is only possible if some conditions are satisfied. So, let's create the state, the possible transitions and its conditions.
The method autoTransitionFrom
will check if is possible do the transition with the actual data
and to what state.
When auto transitioned the state object returned have the ->getData()
with the data used to validate it.
Also, it is possible create the transition with a closure to process the state.
e.g.