Bootstrap

tp6 return之后,为什么还往下执行?

tp6 return之后,为什么还往下执行?

背景:在base控制其中执行权限检查,发现response函数里怎么都不执行

代码:

<?php
namespace app\api\controller;

use think\facade\Log;
use think\facade\Request;
use think\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Exception;

class Base
{

    public function __construct()
    {

        // 控制器初始化
        $this->initialize();
    }
    /**
     * 初始化方法
     */
    protected function initialize()
    {

        //parent::initialize();
        // 在这里可以进行一些初始化操作,例如权限验证、日志记录等
        $this->checkAuth();

    }

    /**
     * 权限验证(示例方法)
     */
    protected function checkAuth()
    {

        try {

            // 获取请求头中的 Authorization 字段
            $authorizationHeader = Request::header('Authorization');

            if (!$authorizationHeader) {
               return   $this->response([], 401, '未提供授权信息!');
            }

            // 提取 JWT 令牌
            $token = str_replace('Bearer ', '', $authorizationHeader);
            if (!$token) {
                return $this->response([], 401, '无效的授权信息!');
            }

            // 定义 JWT 密钥
            $key = 'your_secret_key'; // 请替换为你自己的密钥

            // 验证 JWT 令牌
            $decoded = JWT::decode($token, new Key($key, 'HS256'));

            // 检查用户 ID 是否存在
            if (!isset($decoded->user_id)) {
                return $this->response([], 401, '无效的 JWT 令牌!');
            }

            // 可以在这里进行更多的权限验证逻辑
        } catch (Exception $e) {
            Log::error($e->getMessage());
            return $this->response([], 401, 'JWT 验证失败!');
        }
    }

    /**
     * 统一返回格式
     * @param mixed $data 返回数据
     * @param int $code 状态码
     * @param string $msg 提示信息
     * @return \think\response\Json
     */
    protected function response($data = [], $code = 200, $msg = 'success')
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);

    }

    /**
     * 处理异常
     * @param \Exception $e 异常对象
     * @return \think\response\Json
     */
    protected function handleException(\Exception $e)
    {
        Log::error($e->getMessage());
        return $this->response([], 500, 'Internal Server Error');
    }
}

继承基类的login控制器

<?php
namespace app\api\controller;

use Firebase\JWT\JWT;
use think\facade\Request;

class Login extends Base
{
    public function index()
    {
        // $username = $this->request->post('username');
        // $password = $this->request->post('password');
        $username = Request::post('username');
        $password = Request::post('password');
        // 简单验证用户名和密码,实际项目中应查询数据库
        if ($username === 'your_username' && $password === 'your_password') {

        } else {
            return $this->response([],200,'用户名或密码错误');
            echo 123;
            // return json([
            //     'code' => 401,
            //     'msg' => '用户名或密码错误'
            // ]);
        }
    }
}

代码执行的结果:
在这里插入图片描述

问题:前面的 $this->response([], 401, ‘未提供授权信息!’);压根就没返回!!

然后就是各种查询,豆包,kimi也都问了,然后各种测都不管用!!
只能自己亲自百度查了,最后终于找到了原因和解决办法!

原因

在initailize构造函数里并不能被直接调用,需要通过:->send();exit;来终止

1、重定向

redirect('/admin/index/index')->send();
exit;

2、返回json数据

  $resultArray = [
           'code' => 17002,
           'msg' => Error::ERRORCODE[17002],
           'data' => []
         ];
  json($resultArray)->send();exit;

3、通过HttpResponseException($response);

在 ThinkPHP 6 中,HttpResponseException 是一个特殊的异常类,用于中断当前的执行流程并直接返回一个 HTTP 响应。它通常用于在中间件、控制器或其他地方提前返回响应,同时终止后续的执行。

    protected function response($data = [], $code = 200, $msg = 'success')
    {

         $response = json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
        // 抛出 HttpResponseException,直接返回响应并终止执行
         throw new HttpResponseException($response);
    }

;