Laravel 模型事件的應(yīng)用

在日常處理一些用戶操作事件時(shí),我們有時(shí)候需要記錄下來,方便以后查閱,或者大數(shù)據(jù)統(tǒng)計(jì)。


Laravel 在模型事件中處理起來很方便:https://laravel-china.org/docs/laravel/5.5/eloquent#events


Laravel 的模型事件有兩種方式,

  • 設(shè)置dispatchesEvents屬性映射事件類

  • 使用觀察器來注冊(cè)事件,這里介紹第二種

  • 新建模型
    php artisan make:model Log

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    protected $fillable = ['user_name', 'user_id', 'url', 'event', 'method', 'table', 'description'];
}

  • 創(chuàng)建遷移表:
    php artisan make:migration create_logs_table
  • 表的結(jié)構(gòu)大概是這樣,可按需設(shè)計(jì)
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('logs', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('user_id')->comment('操作人的ID');
            $table->string('user_name')->comment('操作人的名字,方便直接查閱');
            $table->string('url')->comment('當(dāng)前操作的URL');
            $table->string('method')->comment('當(dāng)前操作的請(qǐng)求方法');
            $table->string('event')->comment('當(dāng)前操作的事件,create,update,delete');
            $table->string('table')->comment('操作的表');
            $table->string('description')->default('');
            $table->timestamps();
        });

        DB::statement("ALTER TABLE `logs` comment '操作日志表'");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('logs');
    }
}
  • 運(yùn)行遷移生成表
    php artisan migrate
  • 新建一個(gè)服務(wù)提供者統(tǒng)一注冊(cè)所有的模型事件觀察器(后面的名字可以自己起得形象一點(diǎn))
    php artisan make:provider ObserverLogServiceProvider
  • /config/app.php中的providers數(shù)組注冊(cè)(大概如圖中)
    image
  • app目錄下新建文件夾Observers存放模型觀察器,并新建基類LogBaseServer并在構(gòu)造函數(shù)構(gòu)建基本屬性(CLI是因?yàn)樵诿钚袌?zhí)行時(shí)不存在用戶執(zhí)行)
    image
  • 新建一個(gè)觀察器繼承基類LogBaseServerUser模型,方法的名字要對(duì)應(yīng)文檔中的事件)
    image
  • 到新建的服務(wù)提供者ObserverLogServiceProvider中運(yùn)行
    image
  • 為需要的模型注冊(cè)事件(我這挺多的,之后大概長(zhǎng)這樣)


    image
  • 然后我們觸發(fā)一些事件(增刪改,表的數(shù)據(jù)就有了)


    image

  • 多對(duì)多的關(guān)聯(lián)插入不會(huì)出觸發(fā)模型(比如attach方法)
  • 這時(shí)候就需要自己新建事件類來模擬(這里拿分配權(quán)限給角色粗略說一下)
  1. EventServiceProvider中的listen屬性綁定好事件
    image
  2. 事件PermissionRoleEvent中的注入兩個(gè)參數(shù),一個(gè)是角色,另一個(gè)是attach或者detach返回的數(shù)組
    image
  3. 事件監(jiān)聽器PermissionRoleEventLog也繼承基類LogBaseServer,這里就是根據(jù)傳入的數(shù)組id遍歷,然后創(chuàng)建日志
    image
  4. 之后應(yīng)用事件


    image

  • 更優(yōu)雅的處理登錄注銷事件
  1. EventServiceProvider中的subscribe屬性綁定好處理的類
    image
  2. 事件監(jiān)聽類的方法


    image
  3. 之后的效果就是這樣了:


    image

END

原文地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容