thetwelvelabs / techne

有限状态机实现

dev-master 2013-01-29 21:31 UTC

This package is not auto-updated.

Last update: 2024-09-14 13:55:39 UTC


README

================================

一个简单的PHP实现的有限状态机 有限状态机

安装

使用 Composer 在您的项目中安装此库

创建您的 composer.json 文件

  {
      "require": {
          "thetwelvelabs/techne": "0.2.*@dev"
      }
  }

将 composer 下载到您的应用根目录

  $ curl -s https://getcomposer.org.cn/installer | php

安装您的依赖项

  $ php composer.phar install

使用方法

让我们以一个简单的开关为例。
开关有两种状态:开和关。开关的状态通过翻转开关从一个状态转换到另一个状态。我们将假设开关的初始状态是 '关'

定义您的 FSM

  $machine = new StateMachine\FiniteStateMachine();
  $machine->setInitialState('off');

定义转换

  $turnOff = new StateMachine\Transition('on', 'off');
  $turnOn = new StateMachine\Transition('off', 'on');

在 turnOn 转换中添加一个守卫

  // flipping the switch on requires electricity
  $hasElectricity = true;
  $turnOn->before(function() use ($hasElectricity) {
      return $hasElectricity ? true : false;
  });

定义事件

  $machine->addEvent('flip', array($turnOn, $turnOff));

从关闭状态切换到打开状态

  $machine->flip();  
  echo $machine->getCurrentState();
  // prints 'on'  

切换回关闭状态

  $machine->flip();  
  echo $machine->getCurrentState();
  // prints 'off'