PHP code example of aaronjunker / sssm

1. Go to this page and download the library: Download aaronjunker/sssm library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aaronjunker / sssm example snippets




use sssm\State;
use sssm\StateMachine;

$stateName = new state($stateName, $canLoop);

// State 1 named "State 1" (can loop(default))
$state1 = new state("State 1");
// State 2 named "State 2" (can loop)
$state2 = new state("State 2");
// State 3 named "State 3" (loop not allowed)
$state3 = new state("State 3", false);

// Allowed transitions from state 1 to state 2 
$state1->addAllowedStateTransition($state2);
// Allowed transitions from state 2 to state 3
$state2->addAllowedStateTransition($state3);
// State 3 is not allowed to transition to any other state

$stateMachine = new stateMachine($initialState, $otherState, ...);

$stateMachine = new stateMachine($state1, $state2, $state3);

$stateName->onStateEnter[] = function(State $passedState) {
    // Things that get executed when entering the state
};

$stateName->onLoop[] = function(State $passedState){
    // Things that get executed when the state gets looped
};

$stateName->onStateLeave[] = function(State $passedState){
    // Things that get executed when leaving the state
};

$state1->onStateEnter[] = $state1->onStateEnter[] = function($state){
    echo $state->getStateName()." entered\n";
};

$state1->onLoop[] = function(state $state){
    echo $state->getStateName()." looped\n";
};

$state1->onStateLeave[] = function(state $state){
    echo $state->getStateName()." leaved\n";
};

$stateMachine->loop();

$stateMachine->switchState($newState);

$stateMachine->switchState($state2);
$stateMachine->switchState($state3);

// Returns the current state class
$currentState = $stateMachine->getCurrentState();

echo $stateMachine->getCurrentState() === $state3?"State 3 is current state":"State 3 is not current state";



ssm\state;
use sssm\stateMachine;

$state1 = new state("State 1");
$state2 = new state("State 2");
$state3 = new state("State 3",false);

$state1->addAllowedStateTransition($state2);
$state2->addAllowedStateTransition($state3);

$stateMachine = new stateMachine($state1, $state2, $state3);

$state1->onStateEnter[] = $state2->onStateEnter[] = function($state){
    echo $state->getStateName()." entered\n";
};

$state1->onLoop[] = function(state $state){
    echo $state->getStateName()." looped\n";
};

$state1->onStateLeave[] = function(state $state){
    echo $state->getStateName()." leaved\n";
};


$stateMachine->loop();

$stateMachine->switchState($state2);
$stateMachine->switchState($state3);

echo $stateMachine->getCurrentState() === $state3?"State 3 is current state":"State 3 is not current state";