class User extends Model
{
public static function boot()
{
parent::boot();
self::creating(function($model){
// ... code here
});
self::created(function($model){
// ... code here
});
self::updating(function($model){
// ... code here
});
self::updated(function($model){
// ... code here
});
self::deleting(function($model){
// ... code here
});
self::deleted(function($model){
// ... code here
});
}
}
// App\Providers\AppServiceProvider.php
public function boot()
{
User::observe(UserObserver::class);
}
方法2,使用闭包
可以在模型的静态引导方法中注册自定义事件
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::created(function ($user) {
//
});
}
}
可观察到的事件
// Illuminate\Database\Eloquent\Concerns
/**
* Get the observable event names.
*
* @return array
*/
public function getObservableEvents()
{
return array_merge(
[
'retrieved', 'creating', 'created', 'updating', 'updated',
'saving', 'saved', 'restoring', 'restored', 'replicating',
'deleting', 'deleted', 'forceDeleted', 'trashed'
],
$this->observables
);
}