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);
    }
}
相关推荐
BingoGo17 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack17 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe4 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5