Download the PHP package sofa/state-machine without Composer
On this page you can find all versions of the php package sofa/state-machine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sofa/state-machine
More information about sofa/state-machine
Files in sofa/state-machine
Package state-machine
Short Description Easy to use implementation of the Finite State Machine
License MIT
Informations about the package state-machine
Sofa/StateMachine
Finite State Machine implementation
Installation
Add package to your project:
Usage
State machine helps you eliminate switch
and/or if/else
statements in your code to determine available actions in given state.
Let's use a naive example from a Laravel's Blade view template and underlying Eloquent Order
model:
This quickly gets out of hand, especially when a new status is introduced or the processing order changes.
To streamline it, we can implement state machine for the Order entity:
-
implement interface on the
Order
model -
define available transitions and prepare data for the template:
-
and we end up with controller & template code decoupled from the Process logic & order:
- finally let's process the actions
With this setup we no longer have to change our controllers or views, whenever business requirements change. Instead we add a new transition to the state machine definition.
I need more control during transition - how to?
The above example assumes very simple transition process, ie. $order->status = $new_status
. This can be enough sometimes, but often we will need more flexibility during transitions. To address this need you can customize your Transition
definitions, so they turn from simple POPO into callable
that will be invoked, when state machine processes appropriate action:
Happy Coding!
Contribution
All contributions are welcome. Make your PR PSR-2 compliant and tested.