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" ] }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了