如何在所有模型中使用Common Trait在laravel中实现雄辩的事件 [英] How to implement eloquent events in laravel using commmon Trait for all models

查看:77
本文介绍了如何在所有模型中使用Common Trait在laravel中实现雄辩的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 laravel 5.4 创建一个Web应用程序.

I am using laravel 5.4 to create a web app.

我已经创建了一个特征,以实现针对已创建,更新,删除和还原的口才事件的事件.

I have created a trait to implement events for created, updated, deleted and restored eloquent events.

我创建了一个特征,如下所示:

I have created a trait as below:

<?php

namespace App\Traits;

use Auth;
use App\Master\Activity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * Class ModelEventLogger
 * @package App\Traits
 *
 *  Automatically Log Add, Update, Delete events of Model.
 */
trait ActivityLogger {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function boot()
    {   
        parent::boot();
        foreach (static::getRecordActivityEvents() as $eventName) {
            static::$eventName(function (Model $model) use ($eventName) {
                try {
                    $reflect = new \ReflectionClass($model);
                    return Activity::create([
                        'user_id' => Auth::user()->id,
                        'content_id' => $model->id,
                        'content_type' => get_class($model),
                        'action' => static::getActionName($eventName),
                        'description' => ucfirst($eventName) . " a " . $reflect->getShortName(),
                        'details' => json_encode($model->getDirty()),
                        'ip_address' => Request::ip()
                    ]);
                } catch (\Exception $e) {
                    Log::debug($e->getMessage());//return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getRecordActivityEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
            'restored'
        ];
    }

    /**
     * Return Suitable action name for Supplied Event
     *
     * @param $event
     * @return string
     */
    protected static function getActionName($event)
    {
        switch (strtolower($event)) {
            case 'created':
                return 'create';
                break;
            case 'updated':
                return 'update';
                break;
            case 'deleted':
                return 'delete';
                break;
            case 'restored':
                return 'restore';
                break;
            default:
                return 'unknown';
        }
    }
} 

但是当我在模型中实现它时,例如:

But when I am implementing it in my Model like:

<?php

namespace App\Master;

use App\Traits\ActivityLogger;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LeadSource extends Model
{
    use ActivityLogger;
    use SoftDeletes;

    protected $table = 'lead_source';
    protected $primaryKey = 'lead_source_id';
    protected $dates = ['deleted_at'];
    protected $fillable = [
        'name', 'created_by', 'created_ip', 'updated_by', 'updated_ip'
    ];
}

然后在我的控制器中,我通过雄辩的模型像往常一样调用created/update.但是不会触发事件,也不会在活动表中记录任何内容.

Then in my controller i am calling created/update as usual via eloquent model. But the events aren't fired up and not recording anything in the activity table.

以下是我的迁移活动表:

<?php

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

class CreateActivityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('activity', function (Blueprint $table) {
            $table->increments('activity_id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('content_id');
            $table->string('content_type', 255);
            $table->string('action', 255);
            $table->text('description')->nullable();
            $table->longText('details')->nullable();
            $table->ipAddress('ip_address')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('activity');
    }
}

请告知问题是什么?

推荐答案

我找到了解决方案,对于Model and Migration来说都可以,这就是问题所在.没有.出现问题并阻止其正常运行.

I found the solution, all ok with Model and Migration, it was the trait where it was making issue. There were a no. of things wrong and which was preventing it to work properly.

最重要的错误是日志,我这样做了;它没有包括适当的类,因此引起了问题.

And the most important thing which was wrong is the Log, I did;t included proper class for it and that caused the issue.

这里是仅特征文件的更正代码.

Here is the corrected code for the trait file only.

<?php

namespace App\Traits;

use Auth;
use Request;
use App\Master\Activity;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * Class ModelEventLogger
 * @package App\Traits
 *
 *  Automatically Log Add, Update, Delete events of Model.
 */
trait ActivityLogger {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootActivityLogger()
    {   
        foreach (static::getRecordActivityEvents() as $eventName) {
            static::$eventName(function ($model) use ($eventName) {
                try {
                    $reflect = new \ReflectionClass($model);
                    return Activity::create([
                        'user_id' => Auth::id(),
                        'content_id' => $model->attributes[$model->primaryKey],
                        'content_type' => get_class($model),
                        'action' => static::getActionName($eventName),
                        'description' => ucfirst($eventName) . " a " . $reflect->getShortName(),
                        'details' => json_encode($model->getDirty()),
                        'ip_address' => Request::ip()
                    ]);
                } catch (\Exception $e) {
                    Log::debug($e->getMessage());
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getRecordActivityEvents()
    {
        if (isset(static::$recordEvents)) {
            return static::$recordEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
            'restored'
        ];
    }

    /**
     * Return Suitable action name for Supplied Event
     *
     * @param $event
     * @return string
     */
    protected static function getActionName($event)
    {
        switch (strtolower($event)) {
            case 'created':
                return 'create';
                break;
            case 'updated':
                return 'update';
                break;
            case 'deleted':
                return 'delete';
                break;
            case 'restored':
                return 'restore';
                break;
            default:
                return 'unknown';
        }
    }
} 

请检查并告知是否有任何错误或可以采取更好的方法.

Please check and advise if anything wrong or could be done in better way.

这篇关于如何在所有模型中使用Common Trait在laravel中实现雄辩的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆