出於監控多用戶操作后台的目的,往往需要把各個管理員操作了什么記錄下來。
這個功能用yii2來實現簡直是太簡單了!下邊上代碼~
此demo基於advanced,具體功能可以參考demo 帳號demo 密碼111111
1、在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->primaryKey()[0] . '的' . $desc; $route = Url::to(); $userId = Yii::$app->user->id; $model = new \common\models\AdminLog(); $data = [ 'route' => $route, 'description' => $description, 'user_id' => $userId, 'created_at' => time(), ]; $model->setAttributes($data); $model->save(); } } }
2、在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'] ); },
3、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;
4、用gii生成AdminLog模型:命名空間為common\models