Thinkphp封装统一响应

疑难杂症   2024-04-24 09:03   183   2  

前言

我们平时开发新项目api接口的时候总是要先自定义自己的响应数据格式,但是每个人的风格习惯不同,导致开发人员封装的响应数据格式不统一,而且需要花时间去重复写。本篇文章主要是统一 API 开发过程中「成功」、「失败」以及「异常」情况下的响应数据格式。

封装响应

为了方便调整适合自己的响应格式,这里使用自定义trait来实现

我们新建文件application/common/traits/CustomResponse(基于tp5,其他版本类似),文件内容直接复制下面的代码然后保存,注意修改为你的命名空间:

<?phpnamespace app\common\traits;use think\exception\HttpResponseException;use think\Response;trait CustomResponse{//默认输出类型,可选择json、jsonp、xml、html、view、redirect等//参考thinkphp文档https://doc.thinkphp.cn/v5_1/xiangyingshuchu.htmlprotected $type = 'json';/**
     * 操作成功返回的数据.
     *
     * @param mixed  $data   要返回的数据
     * @param string $msg    提示信息
     * @param int    $code   错误码,默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */protected function success($data = null, $msg = '请求成功', $code = 200, array $header = []){$this->result($msg, $data, $code, $header, 'success');}/**
     * 操作成功返回默认message
     *
     * @param string $msg    提示信息
     */protected function ok($msg = '请求成功'){$this->result($msg,null, 200);}/**
     * 操作失败返回的数据.
     *
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */protected function fail($msg = '请求失败', $data = null, $code = 500, array $header = []){$this->result($msg, $data, $code, $header, 'fail');}/**
     * 系统异常返回的数据.
     *
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */protected function error($msg = '系统异常', $data = null, $code = 500, array $header = []){$this->result($msg, $data, $code, $header, 'error');}/**
     * BadRequest
     *
     */protected function errorBadRequest(){$this->result('400 Bad Request',null, 400, [], 'error');}/**
     * Unauthorized
     *
     */protected function errorUnauthorized(){$this->result('Unauthorized',null, 401, [], 'error');}/**
     * Forbidden
     *
     */protected function errorForbidden(){$this->result('403 Forbidden',null, 403, [], 'error');}/**
     * 404 Not Found
     *
     */protected function errorNotFound(){$this->result('404 Not Found',null, 404, [], 'error');}/**
     * Method Not Allowed
     *
     */protected function errorMethodNotAllowed(){$this->result('Method Not Allowed',null, 405, [], 'error');}/**
     * 返回封装后的 API 数据到客户端.
     *
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型,支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     *
     * @throws HttpResponseException
     * @return void
     */protected function result($msg, $data = null, $code = 200, array $header = [], $status = 'success'){$result = ['code' => $code,'status' => $status, // 状态有success、fail、error3种'msg'  => $msg,'data' => $data,];if (isset($header['statuscode'])) {$code = $header['statuscode'];unset($header['statuscode']);} else {//未设置状态码,根据code值判断$code = $code >= 1000 || $code < 200 ? 200 : $code;}$response = Response::create($result, $this->type, $code)->header($header);throw new HttpResponseException($response);}}

引入trait

在基类控制器或者直接在需要的控制器中引入trait

<?phpnamespace app\index\controller;use app\common\traits\CustomResponse; # 引入trait的命名空间class Controller{use CustomResponse; # 引入trait
    }

注意事项:index模块继承的Controller默认use Jump,里面也有success、fail、error方法,所以同时使用的话会冲突,只能二选一

成功响应

<?phpnamespace app\index\controller;class Index extends Controller{//testpublic function index(){$this->success();}}

更多用法

  • 返回默认message

    $this->ok();//返回结果{"code": 200,"status": "success","msg": "请求成功","data": null}

  • 返回指定message

    $this->ok('提交成功');//返回结果{"code": 200,"status": "success","msg": "提交成功","data": null}

  • 仅返回data

    $data = ['id' => 1, 'name' => 'test'];$this->success($data);//返回结果{"code": 200,"status": "success","msg": "请求成功","data": {"id": 1,"name": "test"}}

  • 返回data和message

    $data = ['id' => 1, 'name' => 'test'];$this->success($data, '成功');//返回结果{"code": 200,"status": "success","msg": "成功","data": {"id": 1,"name": "test"}}

  • 返回data和message并指定状态码

    $data = ['id' => 1, 'name' => 'test'];$this->success($data, '成功', 201);//返回结果{"code": 201,"status": "success","msg": "成功","data": {"id": 1,"name": "test"}}

  • 添加header

    $data = ['id' => 1, 'name' => 'test'];$this->success($data, '成功', 201, ['Content-Type:application/json; charset=utf-8']);//返回结果{"code": 201,"status": "success","msg": "成功","data": {"id": 1,"name": "test"}}

失败响应

  • 返回默认message

    $this->fail();//返回结果{"code": 500,"status": "fail","msg": "请求失败","data": null}

  • 返回指定message

    $this->fail('提交失败');//返回结果{"code": 500,"status": "fail","msg": "提交失败","data": null}

  • data和message

    $data = ['name' => 'test'];$this->fail('提交失败', $data);//返回结果{"code": 500,"status": "fail","msg": "提交失败","data": {"name": "test"}}

  • 返回data和message并指定状态码

    $data = ['name' => 'test'];$this->fail('提交失败', $data, 501);//返回结果{"code": 501,"status": "fail","msg": "提交失败","data": {"name": "test"}}

  • 添加header

    $data = ['name' => 'test'];$this->fail('提交失败', $data, 501, ['Content-Type:application/json; charset=utf-8']);//返回结果{"code": 501,"status": "fail","msg": "提交失败","data": {"name": "test"}}

异常响应

  • 自定义异常

    $this->error('系统异常');//返回结果{"code": 500,"status": "error","msg": "系统异常","data": null}

    用法与失败响应相同,只是status字段有差别

  • Bad Request

    $this->errorBadRequest();//返回结果{"code": 400,"status": "error","msg": "400 Bad Request","data": null}

  • 未登录授权

    $this->errorUnauthorized();//返回结果{"code": 401,"status": "error","msg": "Unauthorized","data": null}

  • 403 Forbidden

    $this->errorForbidden();//返回结果{"code": 403,"status": "error","msg": "Forbidden","data": null}

  • 404 Not Found

    $this->errorNotFound();//返回结果{"code": 404,"status": "error","msg": "404 Not Found","data": null}

  • Method Not Allowed

    $this->errorMethodNotAllowed();//返回结果{"code": 405,"status": "error","msg": "Method Not Allowed","data": null}

内置的方法不是很多,但是应该够用了,如果需要自定义可以在trait中添加自己需要的方法或字段,同样的,封装代码中的提示信息你也可以随便修改。

博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。
闲言碎语
偷一个人的主意是剽窃,偷很多人的主意是研究。
赞赏支持

如果觉得博客文章对您有帮助,异或土豪有钱任性,可以通过以下扫码向我捐助。也可以动动手指,帮我分享和传播。您的肯定,是我不懈努力的动力!感谢各位亲~