YII 系统管理员

来源:互联网 发布:易酷cms包含漏洞维护 编辑:程序博客网 时间:2024/05/18 03:27

出于监控多用户操作后台的目的,往往需要把各个管理员操作了什么记录下来。这个功能用yii2来实现简直是太简单了!下边上代码~ 此demo基于advanced,具体功能可以参考demo 帐号demo 密码111111 在backend目录创建components/AdminLog.php <?ph...

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

此demo基于advanced,具体功能可以参考demo 帐号demo 密码111111

在backend目录创建components/AdminLog.php

<?phpnamespace backend\components;use Yii;use yii\helpers\Url;class AdminLog{    public static function write($event)    {        // 排除日志表自身,没有主键的表不记录(没想到怎么记录。。每个表尽量都有主键吧,不一定非是自增id)        if($event->sender instanceof \common\models\AdminLog || !$event->sender->primaryKey()) {            return;        }        // 显示详情有待优化,不过基本功能完整齐全        if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {            $description = "%s新增了表%s %s:%s的%s";        } elseif($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {            $description = "%s修改了表%s %s:%s的%s";        } else {            $description = "%s删除了表%s %s:%s%s";        }        if (!empty($event->changedAttributes)) {            $desc = '';            foreach($event->changedAttributes as $name => $value) {                $desc .= $name . ' : ' . $value . '=>' . $event->sender->getAttribute($name) . ',';            }            $desc = substr($desc, 0, -1);        } else {            $desc = '';        }        $userName = Yii::$app->user->identity->username;        $tableName = $event->sender->tableSchema->name;        $description = sprintf($description, $userName, $tableName, $event->sender->primaryKey()[0], $event->sender->getPrimaryKey(), $desc);        $route = Url::to();        $userId = Yii::$app->user->id;        $ip = ip2long(Yii::$app->request->userIP);        $data = [            'route' => $route,            'description' => $description,            'user_id' => $userId,            'ip' => $ip        ];        $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_INSERT, ['backend\components\AdminLog', 'write']);        \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_UPDATE, ['backend\components\AdminLog', 'write']);        \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_DELETE, ['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;

原创粉丝点击