systream / 状态机
状态机
1.1.2
2016-06-20 19:17 UTC
Requires
- php: >=5.4.0
- systream/event-dispatcher: ^1.0
Requires (Dev)
- phpmd/phpmd: 2.*
- phpunit/phpunit: ~5.3
This package is not auto-updated.
Last update: 2024-09-14 19:20:02 UTC
README
安装
您可以通过packagist.org使用composer安装此包。
composer require systream/state-machine
composer.json
"require": { "systream/state-machine": "1.*" }
使用示例
设置
您需要向状态机添加转换。
$stateMachine = new StateMachine(new \Systream\EventDispatcher()); $inStock = new StateMachine\State('In stock'); $ordered = new StateMachine\State('Ordered'); $shippingInProcess = new StateMachine\State('Shipping in process'); $deliveredToClient = new StateMachine\State('Order is at client'); $stateMachine->addTransition( new GenericTransition('Order'), $inStock, $ordered ); $stateMachine->addTransition( new GenericTransition('Cancel order'), $ordered, $inStock ); $stateMachine->addTransition( new GenericTransition('Shipping'), $ordered, $shippingInProcess ); $stateMachine->addTransition( new GenericTransition('Handover to client'), $shippingInProcess, $deliveredToClient );
自定义转换
您必须实现\Systream\StateMachine\TransitionInterface接口以创建自定义转换
处理转换
状态对象
要使用状态机,您需要一个具有状态的对象。`process`方法期望\Systream\StateMachine\State\StateObjectInterface接口。
因此,您需要实现它,或者只需使用\Systream\StateMachine\State\StateObjectTrait。
可以
测试它是否可以更改状态为目标状态
$product = new DummyStateObject(); $product->setState($inStock); $stateMachine->can($product, $ordered); // will return true $stateMachine->can($product, $deliveredToClient); // will return false
处理
将项目状态设置为`In Stock`并将其处理为`Ordered`。
$product = new DummyStateObject(); $product->setState($inStock); $stateMachine->process($product, $ordered);
不使用转换设置状态将抛出\Systream\StateMachine\Exception\CantSetStatusException异常。
$product = new DummyStateObject(); $product->setState($inStock); $stateMachine->process($product, $deliveredToClient);
获取可用状态
$states = $stateMachine->getStates();
它将返回一个包含\Systream\StateMachine\State\StateInterface对象的数组
获取下一个状态
此方法将返回状态对象的可能下一个状态
$product = new DummyStateObject(); $states = $stateMachine->getNextStates($product);
它将返回一个包含\Systream\StateMachine\State\StateInterface对象的数组
可视化
使用此库,您能够生成带有状态和转换的图像。为此,您需要安装graphviz。
$doFileGenerator = new StateMachine\DotFileGenerator(); $image = $doFileGenerator->getImage($stateMachine); file_put_contents('my_flow_chart.png', $image);
