I've written a state machine for php. I'm sure you've figured out a solution long ago for this. But for people visiting this page, you are welcome to try out this state machine.
https://github.com/definitely246/state-machine
To use it, you define transition event handlers as classes. Then you need to define transitions. The finite state machine can be configured to do other stuff, but here are the basics.
class Event1ChangedState1ToState2
{
public function allow($context)
{
return true;
}
public function handle($context)
{
if (!$context->statesChanged) $context->statesChanged = 0;
print "state1 -> state2\n";
return $context->statesChanged++;
}
}
class Event1ChangedState2ToState1
{
public function allow($context)
{
return true;
}
public function handle($context)
{
print "state2 -> state1\n";
return $context->statesChanged++;
}
}
You can then define transitions that change states when an event is triggered.
$transitions = [
[ 'event' => 'event1', 'from' => 'state1', 'to' => 'state2', 'start' => true],
[ 'event' => 'event1', 'from' => 'state2', 'to' => 'state1' ],
];
$fsm = new StateMachine\FSM($transitions);
print $fsm->state() . PHP_EOL; // 'state1'
$fsm->event1(); // returns 1, prints 'state1 -> state2'
print $fsm->state() . PHP_EOL; // 'state2'
$fsm->event1(); // returns 2, prints 'state2 -> state1'
print $fsm->state() . PHP_EOL; // 'state1'
You can install with composer
composer require definitely246/state-machine