A dead simple State Machine PHP package.
To install, just add this to your composer.json:
"require": {
"esampaio/state-machine":"master"
}
If you are running PHP 5.3 you need to inherit the StateMachine class:
<?php
use Esampaio\StateMachine\StateMachine;
class MyClass extends StateMachine
{
If you are running PHP version 5.4, just use the Trait:
use Esampaio\StateMachine\Traits\StateMachine;
class MyClass
{
use StateMachine;
To add your possible states and transitions, use the following annotations:
use Esampaio\StateMachine\Traits\StateMachine;
use Esampaio\StateMachine\States;
use Esampaio\StateMachine\Transition;
/**
* @States(states = {"requested", "approved", "rejected"})
* @Transition(state = "requested", transitions = {"approved", "rejected"})
*/
class MyClass
{
use StateMachine;
The following methods will be created for each state:
$foo->isRequested(); // Check if foo's current state equals "requested"
$foo->canApproved(); // Check if foo's current state allows transition to "approved"
$foo->transitionRejected(); // Transitions current foo's state to "rejected"
Two methods are triggered when a transition happens, you may implement them if you want:
$foo->beforeRejected(); // Triggered before foo's state is changed into "rejected"
$foo->afterRejected(); // Triggered after foo's state is changed into "rejected"
Check the source code and/or tests to understand it better.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request