carlescliment / state-machine
一个具有最小依赖的最简有限状态机
0.0.4
2013-09-24 15:09 UTC
Requires
- php: >=5.3.2
This package is not auto-updated.
Last update: 2024-09-23 14:03:25 UTC
README
这是一个简单、无依赖的PHP状态机。
安装
更新你的 composer.json
文件,添加以下依赖项,并运行 php composer.phar update carlescliment/state-machine
"carlescliment/state-machine": "0.0.4"
用法
实现状态机很简单。你需要四个组件:一个具有状态的对象、状态、转换以及状态机。
<?php
use carlescliment\StateMachine\Model\Statable,
carlescliment\StateMachine\Model\StateMachine,
carlescliment\StateMachine\Model\Transition;
class SemaphoreStates
{
const OPEN = 'semaphore.open';
const WARNING = 'semaphore.warning';
const LOCKED = 'semaphore.locked';
public static function all()
{
return array(self::OPEN, self::WARNING, self::LOCKED);
}
}
class SemaphoreTransitions
{
const GIVE_PASS = 'semaphore.give_pass';
const WARN = 'semaphore.warn';
const LOCK = 'semaphore.lock';
}
class Semaphore implements Statable
{
private $state = SemaphoreStates::LOCKED;
public function getState()
{
return $this->state;
}
public function setState($state)
{
$this->state = $state;
return $this;
}
}
class SemaphoreStateMachine extends StateMachine
{
public function __construct()
{
parent::construct();
foreach (SemaphoreStates::all() as $state) {
$this->addState($state);
}
$transitions = array(
new Transition(AuctionTransitions::GIVE_PASS, AuctionStates::LOCKED, AuctionStates::OPEN),
new Transition(AuctionTransitions::GIVE_PASS, AuctionStates::WARNING, AuctionStates::OPEN),
new Transition(AuctionTransitions::WARN, AuctionStates::OPEN, AuctionStates::WARNING),
new Transition(AuctionTransitions::WARN, AuctionStates::LOCKED, AuctionStates::WARNING),
new Transition(AuctionTransitions::LOCK, AuctionStates::OPEN, AuctionStates::LOCKED),
new Transition(AuctionTransitions::LOCK, AuctionStates::WARNING, AuctionStates::LOCKED),
);
foreach ($transitions as $transition) {
$this->addTransition($transition);
}
}
}
现在,你可以使用你的状态机进行操作了
<?php
$semaphore = new Semaphore;
$machine = new SemaphoreStateMachine;
$machine->execute(SemaphoreTransitions::GIVE_PASS, $semaphore);
$machine->execute(SemaphoreTransitions::WARN, $semaphore);
$machine->execute(SemaphoreTransitions::LOCK, $semaphore);