Laravel Observe观察器使用

在laravel中如果对模型进行操作时,可以使用观察器(Observe)对模型监听,进而触发监听事件,包括creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored事件。例如在删除一个数据后,可以在观察器中deleted事件中删除关联数据

1. 创建观察器

php artisan make:observer KolObserver --model=\App\Models\Kol

1.1 观察器类



namespace App\Observers;

use App\Models\Kol;

class KolObserver
{
    /**
     * 在创建完成后调用
     *
     * @param  \App\Models\Kol  $kol
     * @return void
     */
    public function created(Kol $kol)
    {
        //
    }

    /**
     * 在更新完成后调用
     *
     * @param  \App\Models\Kol  $kol
     * @return void
     */
    public function updated(Kol $kol)
    {
        //
    }

    /**
     * 在删除完成后调用
     *
     * @param  \App\Models\Kol  $kol
     * @return void
     */
    public function deleted(Kol $kol)
    {
        //
    }
    
    /**
     * 在删除完成前调用
     *
     * @param  \App\Models\Kol  $kol
     * @return void
     */
    public function deleting(Kol $kol)
    {
        //
    }
}

2. 注册观察器

App\Providers\AppServiceProvider文件中注册观察者



namespace App\Providers;

use App\Models\Kol;
use App\Observers\KolObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Kol::observe(KolObserver::class);
    }
}

3. 调用方法

    public function update(array $data): bool
    {
        $kol = (new Kol())->find($data['id']);//获取模型
        return $kol->update($data);//更新模型数据
    }

以上方法中的update调用Illuminate\Database\Eloquent\Model.phpupdate方法

    public function update(array $attributes = [], array $options = [])
    {
        if (! $this->exists) {
            return false;
        }

        return $this->fill($attributes)->save($options);
    }

以上方法调用save方法,save方法中调用performUpdate方法,在执行updated方法后观察器中的updated监听方法。

    protected function performUpdate(Builder $query)
    {
        // If the updating event returns false, we will cancel the update operation so
        // developers can hook Validation systems into their models and cancel this
        // operation if the model does not pass validation. Otherwise, we update.
        if ($this->fireModelEvent('updating') === false) {
            return false;
        }

        // First we need to create a fresh query instance and touch the creation and
        // update timestamp on the model which are maintained by us for developer
        // convenience. Then we will just continue saving the model instances.
        if ($this->usesTimestamps()) {
            $this->updateTimestamps();
        }

        // Once we have run the update operation, we will fire the "updated" event for
        // this model instance. This will allow developers to hook into these after
        // models are updated, giving them a chance to do any special processing.
        $dirty = $this->getDirty();

        if (count($dirty) > 0) {
            $this->setKeysForSaveQuery($query)->update($dirty);

            $this->syncChanges();

            $this->fireModelEvent('updated', false);
        }

        return true;
    }

4. 注意事项

一定要使用模型中的方法,才能够被监听到。使用DB或以下方法是不能够被观察器监听到

    Kol::where('id', $data['id'])->update($data);

你可能感兴趣的:(PHP,Laravel)