Fluent APIAfter state machine builder was created, we can use fluent API to define state/transition/action of the state machine.
$builder->externalTransition() ->from(self::STATEA) ->to(self::STATEB) ->on(self::EVENTGoToB) ->when($this->checkCondition()) ->perform($this->doAction());
Anexternal transition is built between state 'A' to state 'B' and triggered on received event 'GoToB'.
$builder->internalTransition() ->within(self::STATEA) ->on(self::INTERNAL_EVENT) ->when($this->checkCondition()) ->perform($this->doAction());
Aninternal transition with priority set to high is build inside state 'A' on event 'INTERNAL_EVENT' perform '$this->doAction()'. The internal transition means after transition complete, no state is exited or entered. The transition priority is used to override original transition when state machine extended.
$builder->externalTransition() ->from(self::STATEC) ->to(self::STATED) ->on(self::EVENTGoToD) ->when(newclass ()implements ConditionInterface {publicfunctionisSatisfied($context):bool {echo"Check condition :" .$context ."\n";returntrue; }publicfunctionname():string {return''; } }) ->perform(newclass ()implements ActionInterface {publicfunctionexecute($from,$to,$event,$context):void {echo$context ." from:" .$from ." to:" .$to ." on:" .$event; } }; );Anconditional transition is built from state 'C' to state 'D' on event 'GoToD' when external context satisfied the condition restriction, then call action method.
New State Machine Instance
After user defined state machine behaviour, user could create a new state machine instance through builder. Note, once the state machine instance is created from the builder, the builder cannot be used to define any new element of state machine anymore.
New state machine from state machine builder.
$stateMachine =$builder->build(self::MACHINE_ID);