halfowl / statemachine
使状态机安全且易于使用。
v1.0.0
2023-03-14 16:43 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpstan/phpstan: ^1.10.6
- phpstan/phpstan-phpunit: ^1.3.10
- phpunit/phpunit: ^10.0.16
- psy/psysh: ^0.11.9
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-09-14 20:35:43 UTC
README
使PHP中的状态机安全且易于使用。
安装
使用Composer
$ composer require halfowl/statemachine
示例
想象一个应用程序,它保存文章的状态。它具有以下状态
- 草稿
- 等待校对
- 已发布
新文章从“草稿”开始,进展到“等待校对”,然后到“已发布”。处于“等待校对”的文章可以回到“草稿”状态。
使用这个库,你可以将上述内容建模为
<?php use Halfowl\StateMachine\{State, StateMachine, StateTransition}; $draft = new State("DRAFT"); $awaitingCopy = new State("AWAITING_COPY_EDIT"); $published = new State("PUBLISHED"); // StateTransitions define legal state transitions for the StateMachine. // The second parameter of the constructor takes in an array of States // that the first State can transition to. $fromDraft = new StateTransition($draft, [$awaitingCopy]); // draft->awaiting copy $fromAwaitingCopy = new StateTransition($awaitingCopy, [$draft, $published]); // awaiting copy->draft/published // Put that together into a StateMachine: $sm = new StateMachine( transitions: [ $fromDraft, $fromAwaitingCopy, ], starting: $draft, ); $sm->current(); // => DRAFT $sm->transition($awaitingCopy); // => AWAITING_COPY_EDIT $sm->transition($published); // => PUBLISHED
API
(自动生成的文档正在进行中,跟踪在 #4)
状态
参考:https://github.com/half0wl/php-StateMachine/blob/main/src/StateInterface.php
getName(): string
状态机
参考:https://github.com/half0wl/php-StateMachine/blob/main/src/StateMachineInterface.php
current(): State
can(): bool
is(State $s): bool
transition(State $next): void
状态转换
参考:https://github.com/half0wl/php-StateMachine/blob/main/src/StateTransitionInterface.php
src(): State
dsts(): State[]
inDst(): bool