在日常處理一些用戶操作事件時(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è)觀察器繼承基類
LogBaseServer(User模型,方法的名字要對(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)限給角色粗略說一下)
- 在
EventServiceProvider中的listen屬性綁定好事件
image - 事件
PermissionRoleEvent中的注入兩個(gè)參數(shù),一個(gè)是角色,另一個(gè)是attach或者detach返回的數(shù)組
image - 事件監(jiān)聽器
PermissionRoleEventLog也繼承基類LogBaseServer,這里就是根據(jù)傳入的數(shù)組id遍歷,然后創(chuàng)建日志
image -
之后應(yīng)用事件
image
- 更優(yōu)雅的處理登錄注銷事件
- 在
EventServiceProvider中的subscribe屬性綁定好處理的類
image -
事件監(jiān)聽類的方法
image -
之后的效果就是這樣了:
image












