Thinkphp封装统一响应

前言

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

封装响应

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

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

<?php

namespace 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.html
    protected $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

<?php

namespace app\index\controller;

use app\common\traits\CustomResponse; # 引入trait的命名空间

class Controller{
    use CustomResponse; # 引入trait
    
    
}

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

成功响应

<?php

namespace app\index\controller;

class Index extends Controller
{
    //test
    public 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中添加自己需要的方法或字段,同样的,封装代码中的提示信息你也可以随便修改。

参考文章:

laravel-response: 🤖 Provide a standardized and unified response data format for Laravel and Lumen API projects. - 为 Laravel 和 Lumen API 项目提供一个规范统一的响应数据格式。 - Gitee.com

相关推荐

  1. Thinkphp封装统一响应

    2024-04-23 15:16:06       34 阅读
  2. js请求封装ajax、统一响应

    2024-04-23 15:16:06       33 阅读
  3. 统一返回响应

    2024-04-23 15:16:06       30 阅读
  4. THINKPHP仿Word 统计字数的方法

    2024-04-23 15:16:06       39 阅读
  5. 75.实现统一异常处理和封装统一返回结果

    2024-04-23 15:16:06       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 15:16:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 15:16:06       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 15:16:06       87 阅读
  4. Python语言-面向对象

    2024-04-23 15:16:06       96 阅读

热门阅读

  1. linux 驱动-匹配1 (platform_bus_type)

    2024-04-23 15:16:06       38 阅读
  2. 【根据消息类型实现订阅发布模型】

    2024-04-23 15:16:06       36 阅读
  3. vue中动态引入图片地址需要用require

    2024-04-23 15:16:06       31 阅读
  4. layui数据表格横向滚动条不显示问题

    2024-04-23 15:16:06       27 阅读
  5. cmake命令使用总结

    2024-04-23 15:16:06       28 阅读
  6. 大数据分析:使用Spark和Hadoop的实用指南

    2024-04-23 15:16:06       32 阅读
  7. R语言 数据的整理与清洗(第一篇)

    2024-04-23 15:16:06       35 阅读
  8. 信号量Semaphore

    2024-04-23 15:16:06       28 阅读
  9. 4.2 Python列表(list)

    2024-04-23 15:16:06       38 阅读
  10. OSPF的七种LSA类型

    2024-04-23 15:16:06       34 阅读
  11. 美国公司注册及美国MSB牌照申请流程

    2024-04-23 15:16:06       33 阅读
  12. MyBatis `<foreach>`

    2024-04-23 15:16:06       40 阅读