webman:返回统一格式的json(v1.5.7)

一,php代码:
1,类代码:
app/result/Result.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?php/* 统一格式的返回json数据*/namespace app\result;class Result { //success:code值为0,data:数据 static public function Success($data) { $rs = [ 'code'=>0, 'msg'=>"", 'data'=>$data, ]; return json($rs); } //ErrorCode:需要code/msg参数 static public function ErrorCode($code,$msg) { $rs = [ 'code'=>$code, 'msg'=>$msg, 'data'=>"", ]; return json($rs); } //error,传入定义的数组常量 static public function Error($arr) { $rs = [ 'code'=>$arr['code'], 'msg'=>$arr['msg'], 'data'=>"", ]; return json($rs); }} |
2,controller中调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?phpnamespace app\controller;use support\Request;use app\result\Result;class ImageController{ //图片的列表 public function list(Request $request) { $code = 3001; $msg = "发生数据请求错误"; $res = Result::ErrorCode($code,$msg); return $res; //return Result::Success($image); } //图片的详情 public function detail(Request $request) { $res = ['url'=>'https://wx3.sinaimg.cn/mw690/7f8d08b2gy1hh0qy7n57qj213y0u0wj2.jpg']; return Result::Success($res); }} |
二,测试效果
1,正常返回:

2,返回报错:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/08/18/webman-fan-hui-tong-yi-ge-shi-de-json-v1-5-7/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,查看webman的版本:
liuhongdi@lhdpc:/data/webman/imageadmin$ composer show workerman/webman-framework
name : workerman/webman-framework
descrip. : High performance HTTP Service Framework.
keywords : High Performance, http service
versions : * v1.5.7
...
浙公网安备 33010602011771号