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.
Download byjg/statemachine
More information about byjg/statemachine
Files in byjg/statemachine
Package statemachine
Short Description Finite State Machine implementation with conditional transitions and state actions
License MIT
Informations about the package statemachine
sidebar_key: statemachine tags: [php]
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.
Documentation
- Basic Usage
- Auto Transition
- Error Handling
- Advanced Features
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. Each transition can optionally have a condition that implements TransitionConditionInterface. The canTransition() method receives the data array and returns true or false to allow or deny 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 to do the transition with the actual data
and to what state.
When auto transitioned, the state object returned has the ->getData() method with the data used to validate it.
Processing State with Actions
You can also create a state with an action that will execute when the state is reached.
e.g.
Note: The TransitionConditionInterface validates transitions (returns true/false to allow/deny). The StateActionInterface executes actions when the state is processed.