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);
    }
}
相关推荐
网络安全queen6 小时前
公证 网络安全
开发语言·php
慢一点会很快7 小时前
FRRouting配置与OSPF介绍,配置,命令,bfd算法:
算法·智能路由器·php·ospf
寰宇软件9 小时前
PHP培训机构教务管理系统小程序源码
小程序·uni-app·vue·php
亚历山大海11 小时前
uniapp基于JSSDK 开发微信支付(php后端)
微信·uni-app·php
我是高手高手高高手11 小时前
editor.md编辑器,图片跨域上传,前后端分离
开发语言·编辑器·php
来恩100313 小时前
PHP 性能优化全攻略:提升 Web 应用速度的关键
前端·性能优化·php
-凌凌漆-1 天前
【php】Static 关键字注意事项
开发语言·php
19999er1 天前
文件操作(PHP)(小迪网络安全笔记~
开发语言·网络·笔记·安全·网络安全·php
fakaifa2 天前
云贝餐饮连锁V3独立版全开源+vue源码
微信小程序·小程序·uni-app·开源·php·源码下载
黑客Jack2 天前
Python在网络安全中的应用 python与网络安全
python·web安全·php