非常简单的方法在你的后台添加《系统管理员操作日志》的功能
在backend目录创建components/AdminLog.php
PHP Code复制内容到剪贴板
- <?php
- namespace 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 (!emptyempty($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添加
PHP Code复制内容到剪贴板
- '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表
PHP Code复制内容到剪贴板
- 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 Code复制内容到剪贴板
- php yii gii/model --ns=common\\models --modelClass=AdminLog --tableName=admin_log
下一篇 重写find方法