Laravel观察者模式自动更新ES

Laravel javascript 1131      收藏
Laravel观察者模式

创建observer文件

php artisan make:observer PostObserver --model=Models/Post

在App\Providers\AppServiceProvider下面开启observer

public function boot()
{
     Post::observe(PostObserver::class);
}

监听该模块下的增删改操作

<?php

namespace App\Observers;

use App\Models\Post;
use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Log;

class PostObserver
{
    public function created(Post $post)
    {
        //
    }

    public function updated(Post $post)
    {
        // 监听Post更新操作,更新elasticsearch索引
        $hosts = ['http://ip:9200'];
        $client = ClientBuilder::create()           // Instantiate a new ClientBuilder
        ->setHosts($hosts)      // Set the hosts
        ->build();
    
        $params = [
            'index' => 'es_test',
            'type' => 'lesson',
            'id' => $post->id,
            'body' => [
                'doc' => [
                    'title' => $post->title
                ]
            ]
        ];
        // 在 /my_index/my_type/my_id 中更新文档
        $response = $client->update($params);
    }

    public function deleted(Post $post)
    {
        //
    }

    public function restored(Post $post)
    {
        //
    }

    public function forceDeleted(Post $post)
    {
        //
    }
}

注意:更新数据的时候需要观察者只能监听 ORM Query,如果直接使用post更新是Database Query更新,不能触发观察者更新操作。

Post::where('id', 1)->update(['status'=>1]);

可以替换为如下写法

Post::where('id', 1)->first()->update(['status'=>1]);
// 或者
$model = Post::where('id', 1)->first();
$model->update(['status'=>1]);
$model->save();