PHP code example of demai / business-process

1. Go to this page and download the library: Download demai/business-process 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/ */

    

demai / business-process example snippets


use Demai\BusinessProcess\Entity\BaseEntity;

class Order extends BaseEntity
{
    public function __construct(
        private int $id
    ) {
        // До явной установки статуса свойство state автоматически 
        // защищено объектом NullState
    }

    public function getId(): int
    {
        return $this->id;
    }
}

use Demai\BusinessProcess\State\BaseState;

class NewOrderState extends BaseState
{
    public function getNext(): array
    {
        // Возвращаем объекты состояний, на которые разрешен переход
        return [
            new ProcessingOrderState(),
            new CancelledOrderState()
        ];
    }
}

use Demai\BusinessProcess\StateRouter;

$order = new Order(123);
$order->setState(new NewOrderState()); // Задаем начальное состояние

// Инициализируем роутер (опционально вторым аргументом можно передать ваш PSR-14 EventDispatcher)
$router = new StateRouter($order);

// Выполняем переход с передачей контекста (например, ID пользователя)
$context = ['actor_id' => 42];
$result = $router->setState(new ProcessingOrderState(), false, $context);

if ($result === true) {
    echo "Состояние заказа успешно обновлено!";
} else {
    echo "Переход заблокирован: " . $result; // Например: "incorrect state" или текст ошибки из валидатора
}

use Demai\BusinessProcess\StateChangedEvent;

class OrderNotificationListener
{
    public function __invoke(StateChangedEvent $event): void
    {
        $entity = $event->entity;       // Сама сущность (Order)
        $from = $event->fromState;     // Предыдущее состояние
        $to = $event->toState;         // Новое состояние
        $context = $event->context;   // Переданные метаданные (например, ['actor_id' => 42])
        
        // Ваша логика (отправка писем, логирование действия в аудит-лог и т.д.)
    }
}