PhalApi自定义动态返回JSON根节点,增加最外层返回消息

增加最外层返回消息

使用方法

在API文件中返回前设置需要增加的消息:

\PhalApi\DI()->response->setUserArray('code',2);
\PhalApi\DI()->response->setUserArray('count',100);

结果:

{
    "ret": 200,
    "code": 2,//新增code消息
    "count": 100,//新增count消息
    "msg": "",
    "data": [
        {
            "id": 3,
            "type": "material",
            "url": "http://mes.igeekiot.com/images/material/1575447548763-2019-12-04.jpg",
            "create_time": "2019-12-04 16:19:08"
        },
        {
            "id": 4,
            "type": "material",
            "url": "http://mes.igeekiot.com/images/material/1575448027367-2019-12-04.jpg",
            "create_time": "2019-12-04 16:27:07"
        }
    ]
}

说明

该功能是对原PhalApi\vendor\phalapi\kernal\src\Response.php 文件做了一些修改

修改步骤

1.在abstract class Response{} 中添加$UserArray

    /**
     * @var array $debug 调试信息
     */
    protected $debug = array();
    /**
     * @var array $UserArray 自定义结果
     */
    protected $UserArray = array();

    /** ------------------ setter ------------------ **/

2.增加setUserArray()使用方法

	/**
     * 设置错误信息
     * @param string $msg 错误信息
     * @return Response
     */
    public function setMsg($msg) {
    	$this->msg = $msg;
    	return $this;
    }
	/**
     * 设置用户自定义消息
     * @param   string  $key        键值标识
     * @param   mixed   $value      调试数据
     * @return  Response
     */
    public function setUserArray($key, $value) {
        $this->UserArray[$key] = $value;
        return $this;
    }

3.修改getResault()方法(我这里调整了返回数据的顺序)

	public function getResult() {
	    $rs['ret'] = $this->ret;
	    //将用户数组与rs合并
		$rs = array_merge($rs,$this->UserArray);
		$rs['msg'] = $this->msg;
	    $rs['data'] = is_array($this->data) && empty($this->data) ? (object)$this->data : $this->data;
		
		//添加调试信息
	    if (!empty($this->debug)) {
	        $rs['debug'] = $this->debug;
	    }
	    return $rs;
	}

#增加调试信息

 $x = 'this is x';
 $y = array('this is y');
 \PhalApi\DI()->response->setDebug('x', $x);
 \PhalApi\DI()->response->setDebug('y', $y);
返回
"debug": 
		{
		    "x": "this is x",
		    "y": [
		        	"this is y"
		    	]
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

西安爱极客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值