PHP code example of magdv / workflow-orchestrator

1. Go to this page and download the library: Download magdv/workflow-orchestrator 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/ */

    

magdv / workflow-orchestrator example snippets


        class SimpleWorkflowForTest extends SimpleWorkflow
        {
            public function getGeneratorFlow(): \Generator
            {
                // Выстраиваем по очереди Ваши задачи. Каждая должна возвращаться через yield
                $result = yield new NotifyToMattermostMessage1('Это переменная первой Activity', '111', []);
                yield new NotifyToMattermostMessage1('Результат первой Activity из всего Workflow: ' . $result . ' + еще текст к переменной', '222', []);
            }
        }

        // пример старта WORKFLOW
        $workflowService = new WorkflowService(
            $workflowRepository,
            $workflowBus
        );

        $workflowService->createWorkflow(new SimpleWorkflowForTest('тест'));
        $workflowService->start();

RecoverableExceptionInterface
UnrecoverableExceptionInterface



declare(strict_types=1);

use MagDv\Orchestrator\Enum\WorkflowStatus;
use MagDv\Orchestrator\Events\Events\ActivityErrorLogEvent;
use MagDv\Orchestrator\Events\Events\DispatchActivityEvent;
use MagDv\Orchestrator\Events\Events\DispatchWorkflowEvent;
use MagDv\Orchestrator\Events\Events\WorkflowErrorLogEvent;
use MagDv\Orchestrator\Events\Handlers\DispatchActivityHandler;
use MagDv\Orchestrator\Events\Handlers\DispatchWorkflowHandler;
use MagDv\Orchestrator\Messenger\Handler\ActivityMessageHandler;
use MagDv\Orchestrator\Messenger\Handler\WorkflowMessageHandler;
use MagDv\Orchestrator\Messenger\Message\ActivityMessage;
use MagDv\Orchestrator\Messenger\Message\WorkflowMessage;
use MagDv\Orchestrator\Service\WorkflowService;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;

        // события потребуются джля работы оркестратора
        $eventDispatcher = new EventDispatcher();
        // Можете настроить обработчики события (оповещение, например), когда происходит ошибка в обработке Workflow
        $eventDispatcher->addListener(
            WorkflowErrorLogEvent::class,
            static function (WorkflowErrorLogEvent $event) {}
        );
        // Можете настроить обработчики события (оповещение, например), когда происходит ошибка в обработке Activity
        $eventDispatcher->addListener(
            ActivityErrorLogEvent::class,
            static function (ActivityErrorLogEvent $event) {}
        );

        // ВАШИ реализации репозиториев
        $workflowRepository = new WorkflowRepository();
        $activityRepository = new ActivityRepository();

        
        
        // Настраиваем работу шины workflow
        $workflowMessageHandler = new WorkflowMessageHandler(
            workflowRepository:$workflowRepository,
            eventDispatcher:$eventDispatcher,
            activityRepository: $activityRepository,
        );

        $workflowBus = new MessageBus(
            [
                new HandleMessageMiddleware(
                    new HandlersLocator(
                        [
                            WorkflowMessage::class => [$workflowMessageHandler],
                        ]
                    )
                ),
            ]
        );



        // это то, что мы будем обрабатывать синхронно. Ваши задачи!!!
        $syncBus = new MessageBus(
            [
                new HandleMessageMiddleware(
                    new HandlersLocator(
                        [
                            NotifyToMattermostMessage1::class => [new NotifyToMattermostMessageHandler1()],
                        ]
                    )
                ),
            ]
        );


        // Настраиваем работу шины activity
        $activityMessageHandler = new ActivityMessageHandler(
            activityRepository: $activityRepository,
            eventDispatcher: $eventDispatcher,
            messageBus: $syncBus
        );

        $activityBus = new MessageBus(
            [
                new HandleMessageMiddleware(
                    new HandlersLocator(
                        [
                            ActivityMessage::class => [$activityMessageHandler],
                        ]
                    )
                ),
            ]
        );

        //требуется так же указать обработчики вот этих событий, иначе не будет ничего работать.
        $eventDispatcher->addListener(DispatchActivityEvent::class, new DispatchActivityHandler($activityBus));
        $eventDispatcher->addListener(DispatchWorkflowEvent::class, new DispatchWorkflowHandler($workflowBus));


     
        // создаем сообщение для синхронной ШИНЫ, которое будет обрабатываться через WORKFLOW
        // ЭТО просто пример, Ваш код будет отличаться
        class NotifyToMattermostMessage1
        {
            public function __construct(
                private readonly string $text,
                private readonly string $description,
                private readonly array $context
            ) {
            }
        
            public function getText(): string
            {
                return $this->text;
            }
        
            public function getContext(): array
            {
                return $this->context;
            }
        
            public function getDescription(): string
            {
                return $this->description;
            }
        } 
        
        // Создаем обработчик Вашего сообщения
        final class NotifyToMattermostMessageHandler1
        {
            public function __invoke(NotifyToMattermostMessage1 $message): mixed
            {
                // Тут ваш код, логика какая - то. Результат, который будет возвращаться, можно будет использовать в следующем задании в в этом Workflow
                return 'Результат Activity: ' . $message->getText();
            }
        }
        
        // Пишем ВОРКФЛОУ     
        // Наследуем класс SimpleWorkflow
        class SimpleWorkflowForTest extends SimpleWorkflow
        {
            public function getGeneratorFlow(): \Generator
            {
                // Выстраиваем по очереди Ваши задачи. Каждая должна возвращаться через yield
                $result = yield new NotifyToMattermostMessage1('Это переменная первой Activity', '111', []);
                yield new NotifyToMattermostMessage1('Результат первой Activity из всего Workflow: ' . $result . ' + еще текст к переменной', '222', []);
            }
        }


        // пример старта WORKFLOW
        $workflowService = new WorkflowService(
            $workflowRepository,
            $workflowBus
        );

        $workflowService->createWorkflow(new SimpleWorkflowForTest('тест'));
        $workflowService->start();