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);
    }
}
相关推荐
4***V2027 小时前
PHP在微服务通信中的消息队列
开发语言·微服务·php
亿坊电商7 小时前
PHP框架 vs 原生开发:移动应用后端开发实战对比!
开发语言·php
n***29329 小时前
PHP安全编程实践
开发语言·安全·php
b***748810 小时前
PHP在电子商务系统中的构建
开发语言·php
BingoGo10 小时前
PHP8.6 新的 RFC 提案 Context Managers 优雅管理资源生命周期
后端·php
JaguarJack11 小时前
PHP8.6 新的 RFC 提案 Context Managers 优雅管理资源生命周期
php·服务端
月下的郁王子12 小时前
进阶学习 PHP 中的二进制和位运算
android·学习·php
饭九钦vlog15 小时前
修复重装机kali机器上不了网络域名问题一键脚本
服务器·网络·php
未来之窗软件服务17 小时前
幽冥大陆(二十九)监控平台协议常见地址——东方仙盟练气期
开发语言·php·东方仙盟·东方仙盟sdk·监控协议
拾忆,想起18 小时前
Dubbo网络延迟全链路排查指南:从微服务“快递”到光速传输
网络·网络协议·微服务·架构·php·dubbo