开发者

Finite State Machine with Guards in PHP?

开发者 https://www.devze.com 2023-03-31 17:46 出处:网络
Does anybody know a finite state machine that has guard feature in PH开发者_如何学CP ?Using PEAR\'s FSM (usage example), you can use the action callback to return the next state if the guard fails, li

Does anybody know a finite state machine that has guard feature in PH开发者_如何学CP ?


Using PEAR's FSM (usage example), you can use the action callback to return the next state if the guard fails, like so:

$payload = '';
$fsm = new FSM('STATE1', $payload);
function guard1($symbol, $payload) {
    if ($payload == 'something') {
        // Guard success, allow transition
        return;
    }
    else {
        // Guard fail, return to previous state
        return 'STATE1';
    }
}
$fsm->addTransition('SYMBOL1', 'STATE1', 'STATE2', 'guard1');

$fsm->process('SYMBOL1');


Look at ezComponents Workflow. Allows you to design workflows with many objects and add in conditionals and states.


check out: https://github.com/chriswoodford/techne/tree/v0.2

I think it has the functionality that you're looking for. You define a transition and then can associate a closure that gets called before the transition is processed. here's a simple example:

Define your FSM

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

Define the transitions

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

Add a guard to the turnOn transition

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

Transition from off to on

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

Transition back to off

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

if the $hasElectricity variable had been set to false, the outcome would look like this:

  // oops, forgot to pay that electricity bill
  $hasElectricity = false;

  $turnOn->before(function() use ($hasElectricity) {
      return $hasElectricity ? true : false;
  });

Then, if you try to transition from Off -> On

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

In order to determine where a transition was completed, you'd just have to compare the previous state to the current state.


The Conditions in the Metabor Statemachine https://github.com/Metabor/Statemachine can be used as Guards (3rd parameter in Transition constructor). See Example: https://github.com/Metabor/Statemachine-Example/blob/master/Example/Order/Process/Prepayment.php

0

精彩评论

暂无评论...
验证码 换一张
取 消