aventure-cloud/eloquent-status-recorder

带有历史记录的Eloquent模型状态管理

0.0.7 2018-01-12 09:13 UTC

This package is auto-updated.

Last update: 2024-08-28 01:02:53 UTC


README

Latest Stable Version Total Downloads License

任何eloquent模型都可以通过一个特性来实现状态管理。静态声明状态,但将模型的状态历史存储在数据库中。

安装

composer require aventure-cloud/eloquent-status-recorder

配置

在项目中发布配置文件

php artisan vendor:publish --provider="AventureCloud\EloquentStatusRecorder\EloquentStatusRecorderServiceProvider" --tag="config"

迁移

我们提供了一个迁移脚本以创建statuses表。要发布迁移脚本,请执行

php artisan vendor:publish --provider="AventureCloud\EloquentStatusRecorder\EloquentStatusRecorderServiceProvider" --tag="migrations"

然后使用artisan命令运行

php artisan migrate --path=/database/migrations

使用

HasStatus特性附加到您的模型上,并为每个模型独立配置状态值。

class Order extends Model {
    use HasStatus;
    
    protected $statuses = [
        'opened'    => [],
        'paid'      => ['from'     => 'opened'],
        'approved'  => ['from'     => 'paid'],
        'shipped'   => ['from'     => ['paid', 'approved']],
        'arrived'   => ['from'     => 'shipped'],
        'cancelled' => ['not-from' => ['arrived']],
    ];
}

实用方法

$order = Order::find(1);

/* 
 * Current status
 * instance of model configured in config('eloquent-status-recorder.status_model')
 */
$order->status;

/* 
 * List of all available statuses for current model
 */
$order->statuses();

/* 
 * Available statuses after current status value based on "from" and "not-from" rules
 */
$order->nextAvailableStatuses();

/* 
 * Change status
 */
$order->changeStatusTo('shipped');

自动运行回调

在某些情况下,在设置特定状态后需要执行某些操作。例如,在订单“已发货”后发送电子邮件。此包通过on + status_name (camel cased)约定在状态更改后调用方法。

class Order extends Model {
    use HasStatus;
    
    protected $statuses = [
        'opened'    => [],
        'paid'      => ['from'     => 'opened'],
        'approved'  => ['from'     => 'paid'],
        'shipped'   => ['from'     => ['paid', 'approved']],
        'arrived'   => ['from'     => 'shipped'],
        'cancelled' => ['not-from' => ['arrived']],
    ];
    
    public function onShipped()
    {
        // Send email to the user
    }
}

事件

每次状态更改发生时,都会触发两个事件,并附加当前的Eloquent模型实例和给定状态。

  • StatusChanging(在状态保存之前)
  • StatusChanged(状态更改执行后)