一 、簡單粗魯(用于本地測試)
路由中定義:
Event::listen('eloquent.updated: App\Post',function (){
dump('測試一下修改事件');
});
Route::post('/post/{id}', 'PostController@update');
二 、生成事件和監(jiān)聽器
在 EventServiceProvider 定義對應關系
protected $listen = [
'App\Events\PostEvent' => [
'App\Listeners\PostListener',
],
];
php artisan event:generate //生成文件
event 中注入要操作的類
listen 中handle 方法注入對應事件類
public function handle(PostEvent $event)
{
dump('測試一下修改事件');
}
最后在 post 模型中添加 'events' 屬性
protected $events = [
'updated' => PostListener::class
];
三 、利用框架的 boot 方法
直接在相關
Model
中定義
public static function boot() {
parent::boot();
static::updated(function($model) {
dump('測試一下修改事件');
});
}
四 、定義Trait
如果想對多個模型的updated 或 created 事件進行一些操作,該不會每個模型都單獨寫一個吧.例如:
日志
.
trait LogRecord
{
//注意,必須以 boot 開頭
public static function bootLogRecord()
{
foreach(static::getModelEvents() as $event) {
static::$event(function ($model){
$model->setRemind();
});
}
}
public static function getModelEvents()
{
if(isset(static::$recordEvents)){
return static::$recordEvents;
}
return ['updated'];
}
public function setRemind()
{
dump('記錄邏輯操作');
}
}
然后,在模型中use trait 就可以了.
? creating - 對象已經(jīng) ready 但未寫入數(shù)據(jù)庫
? created - 對象已經(jīng)寫入數(shù)據(jù)庫
? updating - 對象已經(jīng)修改但未寫入數(shù)據(jù)庫
? updated - 修改已經(jīng)寫入數(shù)據(jù)庫
? saving - 對象創(chuàng)建或者已更新但未寫入數(shù)據(jù)庫
? saved - 對象創(chuàng)建或者更新已經(jīng)寫入數(shù)據(jù)庫
? deleting - 刪除前
? deleted - 刪除后
? restoring - 恢復軟刪除前
? restored - 恢復軟刪除后