tamkeen-tech/laravel-enum-state-machine 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

tamkeen-tech/laravel-enum-state-machine

Composer 安装命令:

composer require tamkeen-tech/laravel-enum-state-machine

包简介

Control your state using enums

README 文档

README

Latest Version on Packagist Total Downloads

Introduction

This package simplify controlling the transition between model states, allowing you to prevent unlogically transition and also controlling the initial state of the model using the PHP enums. Each enum allows you to define your states, the allowed transitions and the initial state, all in one place.

Laravel Enum State Machine, also allows you to automatically record the history of the state transition for each define state machine.

This package is built to help developers with the least amount of work needed to get it working.

Installation

You can install the package via composer:

composer require tamkeen-tech/laravel-enum-state-machine

Next, if you going to record the history

php artisan vendor:publish --tag=enum-state-machine-migrations

To publish the config file, you can use the following command:

php artisan vendor:publish --tag=enum-state-machine-configs

Usage

Imagine you have bill with statuses, so at your bill model you will need to use HasStateMachines trait, and define your protected $stateMachines array variable to include all the fields that you going to apply the state machine on, and finally an optional variable protected $recordStateHistory boolean to either save history or not.

use TamkeenTech\LaravelEnumStateMachine\Traits\HasStateMachines;

class Bill extends Model
{
    use HasStateMachines;

    protected $fillable = [
        'status',
    ];

    protected $casts = [
        'status' => BillStatus::class,
    ];

    protected $recordStateHistory = true;

    protected $stateMachines = [
        'status'
    ];
}

In your BillStatus class you need to use trait StateMachine and to add two methods transitions to define your transition array and initialState to define the allowed initial states, both must return array.

use TamkeenTech\LaravelEnumStateMachine\Traits\StateMachine;

enum BillStatus: string
{
    use StateMachine;

    case PENDING = 'PENDING';
    case PAID = 'PAID';
    case EXPIRED = 'EXPIRED';
    case REFUNDED = 'REFUNDED';

    public function transitions(): array
    {
        return match ($this) {
            self::PENDING => [self::PAID, self::EXPIRED],
            self::PAID => [self::REFUNDED]
        };
    }

    public function initialState(): array
    {
        return [self::PENDING];
    }
}

From the example above the allowed transitions for PENDING case are PAID and EXPIRED, and the initail state for bill must be only PENDING

Now you are all done, you can start writing your code safely. So now if your tried to create a bill with different state you will receive an exception.

Example

  • create bill with different initail state

    // throw InitailStateIsNotAllowedException with message "Only allowed initial states: PENDING"
    Bill::create([
      'status' => BillStatus::PAID
    ]);
  • try to update to invalid transition

    $bill = Bill::create([
      'status' => BillStatus::PENDING
    ]);
    
    // throw StateTransitionNotAllowedException with message "Only allowed transition states: PAID, EXPIRED"
    $bill->update([
      'status' => BillStatus::REFUNDED
    ]);

State History Recording

When you enable state history recording by setting protected $recordStateHistory = true in your model, the package will automatically track all state changes for the fields defined in $stateMachines.

Each state change will be recorded in the state_machine_histories table with the following information:

  • The previous state (from)
  • The new state (to)
  • The field name that changed
  • The model type and ID
  • Timestamps of the change

You can access the state history through the stateHistory relationship:

$bill = Bill::find(1);
$bill->stateHistory;

Flow Diagram Generation

You can generate a flow diagram of your state machine using the following command:

php artisan enum:flow-diagram "App\Enums\BillStatus"

You can specify a custom output directory using the --output option

php artisan enum:flow-diagram "App\Enums\BillStatus" --output=/custom/path

This command will create a visual representation of your state machine as a PNG file, making it easier to understand the transitions between states.

Helper Methods

The StateMachine trait provides several helper methods to make working with state transitions easier.

canTransitTo

This method checks if the current state can transition to a given state.

Example

$billStatus = BillStatus::PENDING;

if ($billStatus->canTransitTo(BillStatus::PAID)) {
    // Do something
}

inInitialState

This method checks if the current state is one of the allowed initial states.

Example

$billStatus = BillStatus::PENDING;

if ($billStatus->inInitialState()) {
    // Do something
}

is

This method checks if the current state is equal to a given state.

Example

$billStatus = BillStatus::PENDING;

if ($billStatus->is(BillStatus::PENDING)) {
    // Do something
}

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email theshreif@gmail.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

tamkeen-tech/laravel-enum-state-machine 适用场景与选型建议

tamkeen-tech/laravel-enum-state-machine 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.31k 次下载、GitHub Stars 达 15, 最近一次更新时间为 2022 年 11 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「state」 「enum」 「laravel」 「state-machine」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 tamkeen-tech/laravel-enum-state-machine 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 tamkeen-tech/laravel-enum-state-machine 我们能提供哪些服务?
定制开发 / 二次开发

基于 tamkeen-tech/laravel-enum-state-machine 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.31k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 15
  • 点击次数: 5
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 2
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-11-01