Laravel 模型事件的应用

在平常处理一些用户操做事件时,咱们有时候须要记录下来,方便之后查阅,或者大数据统计。php


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


Laravel 的模型事件有两种方式,数组

  • 设置dispatchesEvents属性映射事件类app

  • 使用观察器来注册事件,这里介绍第二种ide

  • 新建模型 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'];
}
  • 建立迁移表: php artisan make:migration create_logs_table
  • 表的结构大概是这样,可按需设计
<?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('当前操做的URL');
            $table->string('method')->comment('当前操做的请求方法');
            $table->string('event')->comment('当前操做的事件,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');
    }
}
  • 运行迁移生成表 php artisan migrate
  • 新建一个服务提供者统一注册全部的模型事件观察器(后面的名字能够本身起得形象一点) php artisan make:provider ObserverLogServiceProvider
  • /config/app.php中的providers数组注册(大概如图中)
  • app目录下新建文件夹Observers存放模型观察器,并新建基类LogBaseServer并在构造函数构建基本属性(CLI是由于在命令行执行时不存在用户执行)
  • 新建一个观察器继承基类LogBaseServerUser模型,方法的名字要对应文档中的事件)
  • 到新建的服务提供者ObserverLogServiceProvider中运行
  • 为须要的模型注册事件(我这挺多的,以后大概长这样)
  • 而后咱们触发一些事件(增删改,表的数据就有了)

  • 多对多的关联插入不会出触发模型(好比attach方法)
  • 这时候就须要本身新建事件类来模拟(这里拿分配权限给角色粗略说一下)
  1. EventServiceProvider中的listen属性绑定好事件
  2. 事件PermissionRoleEvent中的注入两个参数,一个是角色,另外一个是attach或者detach返回的数组
  3. 事件监听器PermissionRoleEventLog也继承基类LogBaseServer,这里就是根据传入的数组id遍历,而后建立日志
  4. 以后应用事件

  • 更优雅的处理登陆注销事件
  1. EventServiceProvider中的subscribe属性绑定好处理的类
  2. 事件监听类的方法
  3. 以后的效果就是这样了:

END

原文地址大数据

相关文章
相关标签/搜索