萨玛耶 / yii2-audittrail
审计跟踪的移植版
1.3.0
2019-10-02 09:13 UTC
Requires
- yiisoft/yii2: >=2.0
This package is not auto-updated.
Last update: 2024-09-14 15:52:44 UTC
README
这是audittrail 扩展的 Yii2 版本。
安装
安装此扩展的首选方式是通过 composer。
php composer.phar require sammaye/yii2-audittrail
迁移
有两种方法来做这件事
- 将迁移文件(位于
migrations
文件夹内)复制到您的console/migrations
文件夹 - 运行
php yii migrate --migrationPath=@vendor/sammaye/yii2-audittrail/migrations
如何使用
要使用此扩展,您可以简单地将它添加到模型的 behaviou
use yii\db\ActiveRecord; class Model extends ActiveRecord { public function behaviors() { return [ 'sammaye\audittrail\LoggableBehavior' ]; } }
您可以将输入的行为转换为键值结构,以为此模型定义扩展的选项
class Model extends ActiveRecord { public function behaviors() { return [ 'LoggableBehavior' => [ 'class' => 'sammaye\audittrail\LoggableBehavior', 'ignored' => ['some_field'], // This ignores fields from a selection of all fields, not needed with allowed 'allowed' => ['another_field'] // optional, not needed if you use ignore ] ]; } }
这就是设置此扩展的基本方法。
变更
有一些变更。
其中之一是如何为这个扩展定义全局参数。
全局参数的一个例子可能是设置您自己的表名或定义用户模型的位置。
要定义自己的表,您可以在您的 params.php
文件中添加一个名为 audittrail.table
的参数,它将类似于 {{%audit}}
。
要定义自己的用户模型位置,您可以使用 audittrail.model
添加,例如使用值 common\models\User
。
另一个变化实际上与如何查询审计跟踪的最佳方式有关。
下面的示例是上一个文档中的示例,已重写为 Yii2
<?php use yii\data\ActiveDataProvider; use sammaye\audittrail\AuditTrail; use common\models\Title; use common\models\Product; $model_ids = array(array($model->id, Title::className())); foreach($model->products as $id => $product){ $model_ids[] = array($product->id, Product::className()); } $criteria = AuditTrail::find(); $param_id = 0; // $model_ids is the one you built in your original code foreach( $model_ids as $id_pair ) { $criteria->orWhere('model_id = :id' . $param_id . ' AND model = :model' . $param_id); $criteria->addParams([ ':id' . $param_id => $id_pair[0], ':model' . $param_id => $id_pair[1] ]); $param_id++; } $criteria->orderBy(['stamp' => SORT_DESC]); echo yii\grid\GridView::widget([ 'dataProvider' => new ActiveDataProvider([ 'query' => $criteria, 'pagination' => [ 'pageSize' => 100, ] ]), 'columns' => [ [ 'label' => 'Author', 'value' => function($model, $index, $widget){ return $model->user ? $model->user->email : ""; } ], [ 'attribute' => 'model', 'value' => function($model, $index, $widget){ $p = explode('\\', $model->model); return end($p); } ], 'model_id', 'action', [ 'label' => 'field', 'value' => function($model, $index, $widget){ return $model->getParent()->getAttributeLabel($model->field); } ], 'old_value', 'new_value', [ 'label' => 'Date Changed', 'value' => function($model, $index, $widget){ return date("d-m-Y H:i:s", strtotime($model->stamp)); } ] ] ]); ?>
注意
[ 'attribute' => 'model', 'value' => function($model, $index, $widget){ $p = explode('\\', $model->model); return end($p); } ],
这允许我们获取没有命名空间部分的模型名称。
目前在这个扩展中,我将类的完全限定名存储起来
- 利用命名空间创建唯一性
- 以便更容易地使用对象的
className()
函数进行查询。