stayallive / laravel-eloquent-observable
直接从模型中即时注册 Eloquent 模型事件监听器。
v1.0.3
2024-03-13 21:25 UTC
Requires
- php: ^8.0.2
- laravel/framework: ^9||^10||^11
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.14
- orchestra/testbench: ^8|^9
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-09-04 14:04:07 UTC
README
直接从模型中即时注册 Eloquent 模型事件监听器。
使用 观察者 可能会在应用中引入(显著的)开销,因为它们通常在服务提供者中注册,导致每个带有观察者的应用模型在应用启动时都会“启动”,即使模型在请求中从未被触及。此包旨在通过在请求中首次使用 Eloquent 模型时即时连接监听器来减少这种开销。事件回调也定义在模型本身上,使代码更简洁,尽管这当然是我的偏好,如果你不同意,这个包可能不适合你。
注意
Laravel 10.44 引入了 ObservedBy
属性,允许你直接在模型上定义观察者,这否定了此包的所有性能优势。然而,此包仍然提供了在模型本身上定义事件处理器方法的其他方式,因此可能仍然有用,但使用 ObservedBy
属性将解决在服务提供者内部注册模型观察者时的性能问题。
安装
composer require stayallive/laravel-eloquent-observable
使用
添加 Observable
特性将确保可观察的事件连接到模型上定义的事件处理器。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Stayallive\Laravel\Eloquent\Observable\Observable; class SomeModel extends Model { use Observable; // Event handlers are defined by `onEventName` where `EventName` is any valid Eloquent event (or custom event) // See a full list of Eloquent events: https://laravel.net.cn/docs/9.x/eloquent#events public static function onSaving(self $model): void { // For example: $model->slug = str_slug($model->title); } }
安全漏洞
如果你在此包中发现安全漏洞,请发送电子邮件到 Alex Bouma 的 alex+security@bouma.me
。所有安全漏洞都将迅速解决。
许可
此包是开源软件,许可协议为 MIT 协议。