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

数据返回统一格式

app/BaseController.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
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
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

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

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:

composer require firebase/php-jwt

创建自定义中间件 Auth:

前置中间件

<?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);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ThinkPHP6 中,一级路由配置可以通过注解路由或配置文件路由来实现。 #### 1. 注解路由 在控制器类上添加 `@Route` 注解即可定义一级路由。例如: ```php // 注解路由示例 namespace app\controller; use think\annotation\Route; /** * @Route("/admin") */ class Admin { /** * @Route("/") */ public function index() { return 'Hello, Admin!'; } /** * @Route("/user/:id") */ public function user($id) { return 'Hello, User ' . $id . '!'; } } ``` 在上面的示例中,我们在 `Admin` 控制器类上添加了 `@Route("/admin")` 注解,表示将 `/admin` 路径映射到 `Admin` 控制器上。然后,我们在控制器类中定义了 `index()` 和 `user($id)` 两个方法,并分别添加了 `@Route("/")` 和 `@Route("/user/:id")` 注解,表示将 `/admin/` 和 `/admin/user/:id` 路径映射到对应的方法上。 #### 2. 配置文件路由 在 `route` 目录下的 `route.php` 文件中添加路由规则即可定义一级路由。例如: ```php // route/route.php use think\facade\Route; Route::group('/admin', function () { Route::get('/', 'admin/index'); Route::get('/user/:id', 'admin/user'); }); ``` 在上面的示例中,我们使用了 `Route::group()` 方法来定义一级路由,将 `/admin` 路径作为前缀。然后,在 `group` 方法内部使用 `Route::get()` 方法来定义二级路由规则。例如,`Route::get('/', 'admin/index')` 表示将 `/admin/` 路径映射到 `app\controller\Admin` 控制器的 `index()` 方法上。 以上是 ThinkPHP6 中一级路由配置的基本介绍,如果需要更多的路由配置方式,可以参考官方文档:[路由](https://www.kancloud.cn/manual/thinkphp6_0/1037479)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WiFiMing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值