PHP code example of php-architecture-kit / state-machine
1. Go to this page and download the library: Download php-architecture-kit/state-machine 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/ */
php-architecture-kit / state-machine example snippets
use PhpArchitecture\StateMachine\Foundation\StateMachine;
use PhpArchitecture\StateMachine\Foundation\Execution\Execution;
use PhpArchitecture\StateMachine\Foundation\Node\Node;
use PhpArchitecture\StateMachine\Foundation\Node\Identity\NodeId;
use PhpArchitecture\StateMachine\Foundation\Node\Handler\NodeHandlerInterface;
use PhpArchitecture\StateMachine\Foundation\Node\Handler\NodeHandlerContext;
use PhpArchitecture\StateMachine\Foundation\Node\Handler\NodeHandlerResult;
// 1. Define a node
final class SendEmailNode extends Node
{
public function handlerClass(): string
{
return SendEmailHandler::class;
}
}
// 2. Implement the handler
final class SendEmailHandler implements NodeHandlerInterface
{
public function handle(NodeHandlerContext $context): NodeHandlerResult
{
// do work...
return NodeHandlerResult::Continue;
}
}
// 3. Define the workflow
final class OrderWorkflow extends StateMachine
{
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
$send = new SendEmailNode();
$notify = new NotifyAdminNode();
$this->addNode($send)
->addNode($notify)
->addTransition($send->id, $notify->id);
}
}
// 4. Run
$machine = new OrderWorkflow($container);
$execution = Execution::create();
$execution->pointers->startAt($sendNodeId);
$status = $machine->execute($execution);
// ExecutionStatus::Completed | ::Running | ::Suspended
$status = $machine->execute($execution);
interface NodeHandlerInterface
{
public function handle(NodeHandlerContext $context): NodeHandlerResult;
}
$this->addTransition($from->id, $to->id);
// with a condition closure
$this->addTransition($from->id, $to->id, function (States $states): TransitionConditionDecision {
return $states->getState('order') !== null
? TransitionConditionDecision::Accepted
: TransitionConditionDecision::Wait;
});