Laravel提供了很多方式可以監聽去Model的事件(retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored)。
Model會在其生命週期的各個階段促發事件,以刪除該Model實體為例,則促發$this->fireModelEvent('deleted', false);
abstract class Model implements Arrayable, ArrayAccess, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
...
public function delete()
{
...
if ($this->fireModelEvent('deleting') === false) {
return false;
}
...
$this->performDeleteOnModel();
// Once the model has been deleted, we will fire off the deleted event so that
// the developers may hook into post-delete operations. We will then return
// a boolean true as the delete is presumably successful on the database.
$this->fireModelEvent('deleted', false);
return true;
}
...
}
所以透過註冊監聽Model所促發的事件,可以在事件發生時收到通知而加以反應。
1.使用封包
把created事件促發後的反應註冊在User的booted方法中來監聽User的created事件。
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::created(function ($user) {
//
});
}
}
如果希望在某個週期促發客製化的事件時,透過Model的trait:HasEvent中的fireCustomModelEvent方法,可以產生一個客製化的事件。
trait HasEvents
{
...
/**
* Fire a custom model event for the given event.
*
* @param string $event
* @param string $method
* @return mixed|null
*/
protected function fireCustomModelEvent($event, $method)
{
if (! isset($this->dispatchesEvents[$event])) {
return;
}
$result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));
if (! is_null($result)) {
return $result;
}
}
...
}
如下例,透過設定$dispatchesEvents變數為'saved' => UserSaved::class,User的saved發生時,則會促發一個客製化事件:UserSaved。
class User extends Authenticatable
{
use Notifiable;
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'saved' => UserSaved::class
];
}
利用php artisan make:event 來建立UserSaved事件,以 php artisan make:listener ...來監聽UserSaved事件。
如果要監聽一個Model很多事件時,為了集中管理,可以使用Observer,由於是為了集中管理Model很多事件,所以Laravel基本上把很多監聽的設定都處理好了:
(1)為Observer指定要監聽的Model
php artisan make:observer UserObserver --model=User
(2)註冊Observer
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
}
參考文件:
【Laravel-海贼王系列】第十五章,Model Observer 解析
Getting Started with Laravel Model Events