编程学习网 > PHP技术 > Yii2 > Yii2.0后台添加《admin操作日志》的功能
2016
03-14

Yii2.0后台添加《admin操作日志》的功能

出于监控多用户操作后台的目的,往往需要把各个管理员操作了什么记录下来。这个功能用yii2来实现简直是太简单了!下边上代码~

此demo基于advanced
在backend目录创建components/AdminLog.php

<?php

namespace backend\components;

use Yii;
use yii\helpers\Url;

class AdminLog
{
    public static function write($event)
    {
        // 具体要记录什么东西,自己来优化$description
        if(!empty($event->changedAttributes)) {
            $desc = '';
            foreach($event->changedAttributes as $name => $value) {
                $desc .= $name . ' : ' . $value . '=>' . $event->sender->getAttribute($name) . ',';
            }
            $desc = substr($desc, 0, -1);
            $description = Yii::$app->user->identity->username . '修改了' . $event->sender->className() . 'id:' . $event->sender->id . '的' . $desc;
            $route = Url::to();
            $userId = Yii::$app->user->id;
            $data = [
                'route' => $route,
                'description' => $description,
                'user_id' => $userId
            ];
            $model = new \common\models\AdminLog();
            $model->setAttributes($data);
            $model->save();
        }
    }
}

在backend/config/main.php添加

'on beforeRequest' => function($event) {
        \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_UPDATE, ['backend\components\AdminLog', 'write']);
    },

mysql中创建admin_log表

CREATE TABLE `admin_log` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `route` varchar(255) NOT NULL DEFAULT '',
  `description` text,
  `created_at` int(10) NOT NULL,
  `user_id` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

用gii生成AdminLog模型

php yii gii/model --ns=common\\models --modelClass=AdminLog --tableName=admin_log

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取