gpt4 book ai didi

php - Laravel 5,记录模型创建、更新、删除事件

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:37 26 4
gpt4 key购买 nike

我正在开发 Laravel 5 应用程序。我想在其中使用所有新的或更改的(如果正在更新模型)模型字段记录模型创建、更新和删除事件。我想要简单的可重用解决方案,而无需编写太多代码。

最佳答案

当然,您可以创建如下特征并将其用于您要记录的所有模型。

<?php

namespace App\Traits;

use App\Activity;
use Illuminate\Database\Eloquent\Model;

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

/**
* Automatically boot with Model, and register Events handler.
*/
protected static function bootModelEventLogger()
{
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,
'contentId' => $model->id,
'contentType' => get_class($model),
'action' => static::getActionName($eventName),
'description' => ucfirst($eventName) . " a " . $reflect->getShortName(),
'details' => json_encode($model->getDirty())
]);
} catch (\Exception $e) {
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',
];
}

/**
* 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;
default:
return 'unknown';
}
}
}

现在您可以在任何要为其抛出事件的模型中使用此特征。在您的文章模型中。

<?php namespace App;

use App\Traits\ModelEventLogger;
use Illuminate\Database\Eloquent\Model;

class Test extends Model {

use ModelEventLogger;

//Just in case you want specific events to be fired for Article model
//uncomment following line of code

// protected static $recordEvents = ['created'];

}

当然,您必须创建“事件”模型和包含相关列的相关表。我希望这会有所帮助。

关于php - Laravel 5,记录模型创建、更新、删除事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com