jagarsoft/php-state-machine

2.0.1 2022-02-28 23:49 UTC

This package is auto-updated.

Last update: 2024-08-29 05:44:12 UTC


README

StateMachine Logo

Scrutinizer Code Quality Code Coverage Build Status Packagist Downloads language PHP GPL license Badges shields.io

什么是状态机?

它是由两个关键项构成的数据结构

  • 状态
  • 转换

转换是由事件触发的,从初始状态到目标状态。

您可以将状态机视为一个像这样的图1

State diagram for a turnstile

此外,您还可以将其视为一个双入口数组或状态转换表,按当前状态和当前事件索引。内容将是下一个状态1

state-transition-table

绑定到下一个状态,您可以在动作函数中设置一个动作,该动作将在当前状态下触发事件后执行。执行后,将设置新的状态。在上面的示例中,输出可能是绑定函数对伺服电机或其他事物执行的动作(保存数据等)。

您可以在动作函数中调用cancelTransition来取消到下一个状态的转换。当前状态将保持不变。

动作函数是原子的。如果在动作函数中触发新事件,它们将被排队,并且它们的动作函数(如果有),将在每次动作函数返回时依次调用。

如果在嵌套事件中取消转换,如果没有为当前状态定义替代事件,则后续事件可能会失败。

对于当前状态的非预期事件将抛出异常。

您可以通过定义一个带有预期事件和目标状态的addCommonTransition来从任何状态触发常见事件,但您必须添加所有状态。

安装

通过Composer,只需运行以下命令

composer require jagarsoft/php-state-machine

入门

$state_1 = StateEnum::STATE_1;
$state_2 = StateEnum::STATE_2;
$state_3 = StateEnum::STATE_3;

$event_a = EventEnum::EVENT_A;
$event_b = EventEnum::EVENT_B;
$event_c = EventEnum::EVENT_C;

echo PHP_EOL;
$commonAction = function (StateMachine $sm){
    echo "My current state is {$sm->getCurrentState()}".
         " on {$sm->getCurrentEvent()}".
         " and {$sm->getNextState()} will be the next state".PHP_EOL;
};

(new StateMachine())
        ->addState($state_1)
        ->addState($state_2)
        ->addState($state_3)

        ->addTransition($state_1, $event_a, $state_2, $commonAction)
        ->addTransition($state_2, $event_b, $state_3, $commonAction)
        ->addTransition($state_3, $event_c, $state_1, $commonAction)

        ->fireEvent($event_a)
        ->fireEvent($event_b)
        ->fireEvent($event_c)

        ->fireEvent($event_a)
        ->fireEvent($event_b)
        ->fireEvent($event_c);

输出

My current state is 1 on A and 2 will be the next state
My current state is 2 on B and 3 will be the next state
My current state is 3 on C and 1 will be the next state
My current state is 1 on A and 2 will be the next state
My current state is 2 on B and 3 will be the next state
My current state is 3 on C and 1 will be the next state

特性

StateMachine提供以下特性

  1. 您可以在触发事件之前证明一个事件
  2. 您可以通过执行守卫来取消转换
  3. 您可以在动作之前和/或之后执行一个函数
  4. 您可以从ArrayWinzou配置创建StateMachine
  5. 您可以在转换中存储额外的数据

即将推出...您将能够从其他来源创建StateMachine,例如,DOT定义。这样创建的StateMachine将是完全功能的,并将对其事件做出响应。此外,您还将能够将当前StateMachine保存到该格式。

许可证

仅GNU通用公共许可证v2.0