ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 如何使用commmon Trait为所有模型在laravel中实现雄辩事件

2019-07-01 19:17:22  阅读:133  来源: 互联网

标签:php laravel laravel-5-4


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

我创建了一个特征来实现创建,更新,删除和恢复的雄辩事件的事件.

我创建了一个特征如下:

<?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';
        }
    }
} 

但是当我在我的模型中实现它时:

<?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'
    ];
}

然后在我的控制器中,我通过雄辩的模型照常创建/更新.但是事件没有被触发,也没有在活动表中记录任何内容.

以下是我的迁移活动表:

<?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');
    }
}

请告知问题是什么?

解决方法:

我找到了解决方案,模型和迁移都可以,这是它产生问题的特征.有没有.事情错了,这阻碍了它正常运作.

最重要的是错误的是Log,我做了;包括适当的类,它引起了问题.

以下是特征文件的更正代码.

<?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';
        }
    }
} 

请检查并告知是否有任何错误或可以更好地完成.

标签:php,laravel,laravel-5-4
来源: https://codeday.me/bug/20190701/1349701.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有