PHP code example of konsulting / fluent-state-machine
1. Go to this page and download the library: Download konsulting/fluent-state-machine library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
konsulting / fluent-state-machine example snippets
use Konsulting\StateMachine\StateMachine;
$door = new StateMachine(['closed', 'open'])
->addTransition('open')->from('closed')->to('open')
->addTransition('close')->from('open')->to('closed');
$door->transition('open'); // will complete successfully
$door->transition('close'); // will throw a TransitionFailed Exception
use Konsulting\StateMachine\StateMachine;
$simpleDoor = new SimpleDoor();
$sm = new StateMachine(['closed', 'open'])
->setModel($state)
->addTransition('open')->from('closed')->to('open')
->addTransition('close')->from('open')->to('closed');
$sm->transition('open'); // outputs opening
echo $sm->getCurrentState(); // outputs open
$sm->transition('close'); // outputs closing
echo $sm->getCurrentState(); // outputs closed
class SimpleDoor
{
public function open()
{
echo "opening";
}
public function close()
{
echo "closing";
}
}
$door = new Door('closed');
$door->close(); // throws TransitionFailed Exception.
$door->open(); // outputs "I am opening"
$door->close(); // outputs "I am closing"
class Door
{
public $state;
protected $stateMachine;
public function __construct($state)
{
$this->state = $state;
$this->stateMachine = new AttachedStateMachine($this);
}
public function open()
{
$this->stateMachine->transition('open', function () {
echo "I am opening";
});
}
public function close()
{
$this->stateMachine->transition('close', function () {
echo "I am closing";
});
}
}
use Konsulting\StateMachine\AttachableStateMachine;
use Konsulting\StateMachine\StateMachine;
use Konsulting\StateMachine\TransitionFactory;
use Konsulting\StateMachine\Transitions;
class AttachedStateMachine extends AttachableStateMachine
{
protected function define()
{
$transitionFactory = (new TransitionFactory)->useDefaultCall(false);
$transitions = new Transitions($transitionFactory);
$this->setTransitions($transitions)
->setStates(['closed', 'open'])
->setCurrentState($this->model->state ?? 'closed')
->addTransition('open')->from('closed')->to('open')
->addTransition('close')->from('open')->to('closed');
}
public function setCurrentState($state)
{
if ($this->model) {
$this->model->state = $state;
}
return parent::setCurrentState($state);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.