我正在构建一个 package 来记录 eloquent 上发生的更改,并且我正在尝试找出要检查的内容以在
updated
时忽略 restored
事件。
trait HasLogs
{
public static function bootHasLogs(): void
{
// created ...
self::updated(callback: fn ($model) => self::log($model, 'updated'));
self::deleted(callback: function ($model) {
// Ignore 'deleted' event when 'softDeleted' or 'forceDeleted'
if (in_array('Illuminate\Database\Eloquent\SoftDeletes', (class_uses(self::class)))) {
return;
}
self::log($model, 'deleted');
});
if (in_array('Illuminate\Database\Eloquent\SoftDeletes', (class_uses(self::class)))) {
// softDeleted ...
self::restored(callback: fn ($model) => self::log($model, 'restored'));
// forceDeleted ...
}
}
// ...
}
以下是操作顺序(如果有帮助的话):
Model::restore()
关于SoftDeletes
特质。restoring
被解雇了。Model::save()
saving
已被解雇。Model::performUpdate()
updating
已被解雇。Builder::update()
updated
已被解雇。Model::finishSave()
saved
已被解雇。restored
被解雇了。特征
HasLogs
为 Model
添加了一个布尔属性,名为 loggableIsBeingRestored
,默认设置为 false
。
该特征还为
restoring
注册了一个新的侦听器,在请求所描述的操作时将 loggableIsBeingRestored
设置为 true
。
然后
updated
侦听器会在继续执行其操作之前检查 loggableIsBeingRestored
。
trait HasLogs
{
public bool $loggableIsBeingRestored = false;
public static function bootHasLogs(): void
{
// ...
self::updated(callback: function ($model) {
if (isset($model->loggableIsBeingRestored) && $model->loggableIsBeingRestored) {
// This is a restored event so don't log!
return;
}
self::log($model, 'updated');
});
// ...
self::restored(callback: function ($model) {
self::log($model, 'restored');
$model->loggableIsBeingRestored = false;
});
self::restoring(callback: function ($model) {
$model->loggableIsBeingRestored = true;
});
}
// ...
}
有很多更直接的方法可以解决这个问题。其中之一是使用观察者:
<?php
namespace App\Observers\User;
use App\Models\User;
class UserObserver {
/**
* Handle the User "created" event.
*/
public function created(User $user): void {
// do work
}
/**
* Handle the User "updated" event.
*/
public function updated(User $user): void {
if (!$user->wasChanged('deleted_at')) { // <- ignore when this field changes
// do work
}
}
/**
* Handle the User "deleted" event.
*/
public function deleted(User $user): void {
// do work
}
/**
* Handle the User "restored" event.
*/
public function restored(User $user): void {
// do work
}
}