Laravel 事件侦听的几个方法 [Trait, Model boot(), Observer Class]

1 Trait

1.1 可以在 Trait 中定义一个静态的 bootFooBar() 方法,注:FooBar 是你的 Trait 名称

namespace AppTraits;


use AppArchive;

trait HasArchive
{
public static function bootHasArchive()
{
static::creating(function($model) {
info("Trait [HasArchive] creating...");
});
static::deleting(function($model) {
$model->archive()->delete();
});
}

/**
* Model has an archive.
*
* @return mixed
*/
public function archive()
{
return $this->morphOne(Archive::class, 'model_has_archive');
}
}
1.2 这种方式非常适合用来对关联中间表中的数据进行相应处理

2 Model
2.1 定义静态的 boot() 方法
namespace App;

use AppTraitsHasArchive;
use IlluminateDatabaseEloquentModel;
use KalnoyNestedsetNodeTrait;

class Area extends BaseModel
{
use HasArchive;
use NodeTrait;

protected $table = 'areas';
protected $guarded = [];

public static function boot()
{
parent::boot();
static::creating(function (Area $area) {
info("Model [Area] creating...");
});
}

}
2.2 这种方式定义起来比较简单粗暴,直接有效

3 利用 Observer 类
3.1 这种方法就不举例了,官方文档可查阅
3.2 此种方式,代码分离比较合理
3.3 建议,除了使用 Trait 方式复用代码外,都应该采用这种方法

4 小结
4.1 经测试,对事件的侦听,可在以上三种方式中都实现,不会相互覆盖。Laravel 会顺序调用
原文地址:https://www.cnblogs.com/mouseleo/p/10915905.html