增加最外层返回消息
使用方法
在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"
]
}