State - State machines made simple.

Build Status Total Downloads Latest Stable Version Latest Unstable Version License

State is a state machine implementation in PHP.

Install

Pull State in from Composer:

composer require offbeatengineer/state "^v1.3"

Create a state machine

Creating a state machine with State is a cinch. Just pass a machine spec, which is a specially formatted string description, to the machine into the constructor, like the following:

<?php
use OffbeatEngineer\State\Machine;

...

$order->state = new Machine("states: placed, payed, shipped, completed
               - pay:      placed  > payed
               - ship:     payed   > shipped
               - complete: shipped > completed");
?>

The machine spec starts with one line enumerating all states, namely placed, payed, shipped and completed. The first state (placed) will be treated as the initial state.

states: placed, payed, shipped, completed

Following the states line, subsequent lines each describes one possible transition. E.g.:

- pay: placed  > payed

The above line defines a transition named pay that changes the state of the machine from placed to payed.

You can provide an optional second argument to the constructor to indicate the current state of the machine.

<?php
$order->state = new Machine("...", "payed"); // machine set to 'payed' state
?>

Teleporting

A teleport() method is at your disposal if you would like to set the machine to a specific state after instantiation.

<?php
$order->state = new Machine("..."); // machine already instantiated
...
$order->teleport("shipped"); // machine set to 'shipped' state
?>

Note that the teleport() method does nothing but setting the machine state. None of the transition listeners will be called since no transition is performed. What happened here is a teleport! :P