jpkleemans/attribute-events

🔥 在Eloquent模型属性变更时触发事件

1.5.0 2023-12-14 14:48 UTC

This package is auto-updated.

Last update: 2024-09-21 09:06:16 UTC


README

Laravel Attribute Events Laravel Attribute Events

Build Status Last Updated Latest Stable Version License

class Order extends Model
{
    protected $dispatchesEvents = [
        'status:shipped' => OrderShipped::class,
        'note:*' => OrderNoteChanged::class,
    ];
}

Eloquent模型在其生命周期中会触发一些方便的事件,如createddeleted。然而,在模型的生命周期中通常还有许多更具业务意义的事件发生。使用这个库,您可以通过将属性更改映射到您自己的事件类来捕获这些事件。

安装

composer require jpkleemans/attribute-events

如何使用它

在您的模型中使用Kleemans\AttributeEvents特质,并将属性添加到$dispatchesEvents属性中

class Order extends Model
{
    use AttributeEvents;

    protected $dispatchesEvents = [
        'created'         => OrderPlaced::class,
        'status:canceled' => OrderCanceled::class,
        'note:*'          => OrderNoteChanged::class,
    ];
}

属性事件将在更新后的模型保存后触发。每个事件通过其构造函数接收模型实例。

有关模型事件和$dispatchesEvents属性的更多信息,请访问Laravel 文档

监听

现在您可以通过EventServiceProvider$listen数组订阅事件,或者使用基于闭包的监听器手动订阅

Event::listen(function (OrderCanceled $event) {
    // Restock inventory
});

或者使用Laravel的广播功能向用户推送实时更新

Echo.channel('orders')
    .listen('OrderShipped', (event) => {
        // Display a notification
    })

JSON属性

对于存储为JSON的属性,您可以使用->运算符

protected $dispatchesEvents = [
    'payment->status:completed' => PaymentCompleted::class,
];

访问器

对于更复杂的状态变化,您可以使用由访问器定义的属性

class Product extends Model
{
    protected $dispatchesEvents = [
        'low_stock:true' => ProductReachedLowStock::class,
    ];

    public function getLowStockAttribute(): bool
    {
        return $this->stock <= 3;
    }
}

您还可以使用Laravel 9中引入的定义访问器的新方法

了解更多

赞助商

Nexxtmove Logo

感谢Nexxtmove赞助本项目的开发。
在这里放置您的标志或名称? 赞助此项目

许可证

代码在MIT许可证下发布。