thinkphp 利用中间件 实现日志操作记录

1,634 阅读1分钟

声明,本文大部分代码都是参考esayadmin框架,地址:github.com/zhongshaofa…

SystemLogService.php

<?php
/**
 * Created by.
 * User: Jim
 * Date: 2020/10/16
 * Time: 10:23
 */

namespace app\index\services;


use think\Db;
use think\facade\Config;

class SystemLogService
{
    /**
     * 实例
     * @var null
     */
    protected static $instance = null;

    /**
     * 表前缀
     * @var string
     */
    protected $tablePrefix;

    /**
     * 表后缀
     * @var string
     */
    protected $tableSuffix;

    /**
     * 表名
     * @var string
     */
    protected $tableName;

    protected function __construct()
    {
        $this->tablePrefix = Config::get('database.prefix');
        $this->tableSuffix = date('Ym', time());
        $this->tableName = "{$this->tablePrefix}system_log_{$this->tableSuffix}";
    }

    protected function __clone()
    {
        // TODO: Implement __clone() method.
    }


    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }

        return self::$instance;
    }


    public function save($data = [])
    {
        if (empty($data)) return false;
        $this->detectTable();

        Db::startTrans();
        try {
            Db::table($this->tableName)->insert($data);
            Db::commit();
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return true;
    }


    protected function detectTable()
    {
        $check = Db::query("show tables like '{$this->tableName}'");

        if (empty($check)) {
            $sql = $this->getCreateSql();
            Db::execute($sql);
        }
        return true;
    }


    /**
     * 根据后缀获取创建表的sql
     * @return string
     */
    protected function getCreateSql()
    {
        return <<<EOT
CREATE TABLE `{$this->tableName}` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `admin_id` int(10) unsigned DEFAULT '0' COMMENT '管理员ID',
  `url` varchar(1500) NOT NULL DEFAULT '' COMMENT '操作页面',
  `method` varchar(50) NOT NULL COMMENT '请求方法',
  `title` varchar(100) DEFAULT '' COMMENT '日志标题',
  `content` text NOT NULL COMMENT '内容',
  `ip` varchar(50) NOT NULL DEFAULT '' COMMENT 'IP',
  `useragent` varchar(255) DEFAULT '' COMMENT 'User-Agent',
  `create_time` int(10) DEFAULT NULL COMMENT '操作时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=630 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='后台操作日志表 - {$this->tableSuffix}';
EOT;
    }


}

注册中间件

创建文件

php think make:middleware AdminAuth

代码:

<?php

namespace app\http\middleware;

use app\Admin\services\SystemLogService;

class AdminAuth
{
    public function handle($request, \Closure $next)
    {
//        if (condition..) {
//
//        }
        $data['admin_id'] = 'admin_id';
        $data['url'] = 'url';
        $data['method'] = 'method';
        $data['title'] = 'title';
        $data['content'] = 'content';
        $data['ip'] = 'ip';
        $data['useragent'] = 'useragent';
        $data['create_time'] = 'create_time';
        SystemLogService::instance()->save($data);
        return $next($request);
    }
}

配置中间件

来到 middleware.php配置文件中, 如果不存在,则创建

配置内容

<?php
/**
 * Created by.
 * User: Jim
 * Date: 2020/10/16
 * Time: 9:16
 */
return [
    \app\http\middleware\AdminAuth::class,
];