jxckaroo / laravel-state-machine

Laravel的一个简单状态机,用于处理模型事务,基于预定义规则。

v1.1.0 2022-02-01 21:07 UTC

This package is auto-updated.

Last update: 2024-09-09 16:57:43 UTC


README

Latest Version on Packagist Total Downloads GitHub Actions GitHub Actions GitHub Actions

一个简单的状态机,允许根据预定义的规则转换模型状态。

安装

您可以通过composer安装此包

composer require jxckaroo/laravel-state-machine

运行包迁移

php artisan migrate

用法

Jxckaroo\StateMachine\Stateable 特性添加到需要状态管理的模型中,并在您的模型上定义您的状态

状态与规则

下面是一个现成的模型示例。

use Illuminate\Database\Eloquent\Model;
use Jxckaroo\StateMachine\Stateable;

class Order extends Model
{
    use Stateable;

    protected array $states = [
        'factory' => ExampleRule::class,
        'complete' => [
            ExampleRule::class,
            ExampleRuleFalse::class
        ]
    ];

    // ...
}

在定义您的状态时,您可以指定一个或多个规则,如上所示。您的规则必须扩展 Jxckaroo\StateMachine\Contracts\StateRule 并包含一个 validate 方法,如下例所示

class ExampleRule extends StateRule
{
    public function validate(Model $model): bool
    {
        return $model->getKey() !== null;
    }
}

您还可以在验证失败时添加特定的错误消息,如下所示

class ExampleRuleFailure extends StateRule
{
    public function validate(Model $model): bool
    {
        if (!$model->isProductionReady()) {
            $this->addError("Model is not ready for production.");
            return false;
        }

        return true;
    }
}

然后,在尝试转换状态后,您可以通过调用 $model->stateErrors() 来检索这些错误消息,结果返回一个错误集合,如下所示

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => Array
                (
                    [message] => Model is not ready for production.
                    [rule] => Jxckaroo\StateMachine\Rules\ExampleRuleFailure
                )

        )

    [escapeWhenCastingToString:protected] =>
)

模型交互

// Get model
$order = Order::find(1);

// Get current state of a model
$order->state;

// Get the state history of a model
$order->stateHistory;

// Attempt to transition model to one of your defined states
$order->transitionToState("factory");

// Attempt to transition model to previous state as defined in $order->states
$order->transitionToPreviousState();

// Attempt to transition model to next state as defined in $order->states
$order->transitionToNextState();

// Get all available states on model
$order->states();

检查状态转换是否成功

$order = Order::find(1);

if ($order->transitionToState("complete")->isSuccessful()) {
    // Successful transition
} else {
    // Get a collection of all rules that failed
    $order->stateErrors();
}

测试

composer test

更新日志

有关最近更改的更多信息,请参阅更新日志

贡献

有关详细信息,请参阅贡献指南

安全

如果您发现任何安全相关的问题,请通过电子邮件jack@javeloper.co.uk而不是使用问题跟踪器。

鸣谢

许可

MIT许可(MIT)。有关更多信息,请参阅许可文件

Laravel包模板

此包是用Laravel包模板生成的。