thinkphp6项目初始化配置方案二次修正版本

数据返回统一格式

app/BaseController.php新增文件内容在末尾,并在构造函数中实例化数据模型类

php 复制代码
// 成功统一返回格式
function Result($data, $msg = '', $code = 200, $httpCode = 200): \think\response\Json
{
    $res = [
        'code' => $code,
        'msg'  => $msg,
        'data' => $data
    ];
    return json($res, $httpCode);
}

// 成功返回,无数据格式
function ResultOK($msg = 'ok', $code = 200, $httpCode = 200): \think\response\Json
{
    $res = [
        'code' => $code,
        'msg'  => $msg,
        'data' => null
    ];
    return json($res, $httpCode);
}

// 失败返回
function ResultError($msg = "error", $code = 400, $httpCode = 200): \think\response\Json
{
    $res = [
        'code' => $code,
        'msg'  => $msg,
        'data' => null
    ];
    return json($res, $httpCode);
}

在config目录新建redis.php

php 复制代码
<?php
return [
    //激活Token
    "active_pre" => "active_account_pre_",
    //登录Token
    "token_pre" => "access_token_pre_",
    //登录Token过期时间
    "login_expire" => 24 * 3600,
    //重置密码Token
    "reset_pre" => "reset_password_pre_",
    //登录验证码
    "code_pre" => "login_pre_",
    //登录验证码过期时间
    "code_expire" => 120,
    //登录验证码错误次数
    "code_error" => 3,
    //文件数据过期时间
    "file_expire" => 3600 / 4,
];

修改全局报错返回数据样式app/ExceptionHandle.php

php 复制代码
<?php
namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息(日志)的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息(包括日志或者其它方式记录)
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render(\think\Request $request, Throwable $e): Response
    {
        // 自定义异常处理机制
        $response = [
            'code' => 500,
            'msg'  => $e->getMessage(),
            'data' => null,
        ];

        return json($response);
    }
}

修改缓存配置config/cache.php

php 复制代码
<?php

// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------

return [
    // 默认缓存驱动
    'default' => 'redis',

    // 缓存连接方式配置
    'stores'  => [
        'file' => [
            // 驱动方式
            'type'       => 'File',
            // 缓存保存目录
            'path'       => '',
            // 缓存前缀
            'prefix'     => '',
            // 缓存有效期 0表示永久缓存
            'expire'     => 0,
            // 缓存标签前缀
            'tag_prefix' => 'tag:',
            // 序列化机制 例如 ['serialize', 'unserialize']
            'serialize'  => [],
        ],
        // 更多的缓存连接
        'redis'=>[
            // 驱动方式
            'type'       => 'redis',
            // 服务器地址
            'host'       => '****',
            // 服务器端口
            'port'       => 6379,
            // 密码
            'password'   => '',
            // 缓存有效期 0表示永久缓存
            'expire'     => 0
        ]
    ],
];

给用户颁发jwt鉴权证书

安装 firebase/php-jwt:

bash 复制代码
composer require firebase/php-jwt

创建自定义中间件 Auth:

前置中间件

php 复制代码
<?php
namespace app\middleware;

use think\Middleware;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Config;
use think\Request;
use think\Response;

class Auth extends Middleware
{
    public function handle(Request $request, \Closure $next)
    {
        // 从请求头获取JWT
        $token = $request->header('Authorization');

        if (!$token) {
            return json(['code' => 401, 'msg' => '未提供Token', 'data' => null], 401);
        }

        try {
            // 解析JWT
            $decoded = JWT::decode($token, new Key(Config::get('app.jwt_secret'), 'HS256'));
            $userId = $decoded->uid;

            // 查询用户信息
            $user = Db::table('staff')->where('id', $userId)->where('status', 1)->find();
            if (!$user) {
                return json(['code' => 403, 'msg' => '账户异常', 'data' => null], 403);
            }

            // 将用户信息传递给控制器
            $request->user = $user;
        } catch (\Exception $e) {
            return json(['code' => 401, 'msg' => '账号或密码错误', 'data' => null], 401);
        }

        return $next($request);
    }
}
相关推荐
Flying_Fish_roe37 分钟前
linux-网络管理-网络配置
linux·网络·php
Book_熬夜!9 小时前
Python基础(九)——正则表达式
python·正则表达式·php
计算机学姐9 小时前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
BLEACH-heiqiyihu10 小时前
红帽9中nginx-源码编译php
运维·nginx·php
翔云API10 小时前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php
白总Server11 小时前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
fakaifa11 小时前
八戒农场小程序V2最新源码
小程序·uni-app·php·生活·开源软件
吱吱鼠叔12 小时前
MATLAB方程求解:1.线性方程组
开发语言·matlab·php
Messiah___13 小时前
【论文阅读】Slim Fly: A Cost Effective Low-Diameter Network Topology 一种经济高效的小直径网络拓扑
开发语言·php