Finite is a state machine library that gives statefulness to your PHP objects by defining a states and transitions graph applicable to these objects.
$ curl -s http://getcomposer.org/installer | php $ php composer.phar init $ php composer.phar require yohang/finiteView on Github
<?php
$document = new MyDocument;
$stateMachine = new Finite\StateMachine\StateMachine;
$loader = new Finite\Loader\ArrayLoader([
'class' => 'MyDocument',
'states' => [
'draft' => ['type' => 'initial', 'properties' => []],
'proposed' => ['type' => 'normal', 'properties' => []],
'accepted' => ['type' => 'final', 'properties' => []],
'refused' => ['type' => 'final', 'properties' => []],
],
'transitions' => [
'propose' => ['from' => ['draft'], 'to' => 'proposed'],
'accept' => ['from' => ['proposed'], 'to' => 'accepted'],
'refuse' => ['from' => ['proposed'], 'to' => 'refused'],
]
]);
$loader->load($stateMachine);
$stateMachine->setObject($document);
$stateMachine->initialize();
<?php
class MyDocument implements Finite\StatefulInterface
{
private $state;
public function getFiniteState()
{
return $this->state;
}
public function setFiniteState($state)
{
$this->state = $state;
}
}
<?php
echo $stateMachine->getCurrentState();
// => "draft"
var_dump($stateMachine->can('accept'));
// => bool(false)
var_dump($stateMachine->can('propose'));
// => bool(true)
$stateMachine->apply('propose');
echo $stateMachine->getCurrentState();
// => "proposed"