/**返回一个jason **/ trait RespoenseJson { public function jsonSucessData($data = []) { return $this->jsonResponse(code:0,message:'Success',$data); } public function jsonResponse($code,$message,$data) { $content = [ 'code'=> $code, 'msg' => $message, 'data'=> $data, ]; json_encode($content); } }
接口三要素:
code:展示和记录错误码 code=0,是成功
msg:给人和测试看状态情况,msg:"成功"也是成功的意思
data:传输数据
Json接口:
1、data:表示所传递和收到的数据内容
2、msg:是返回获取状态。用字符串的值做打印判断是否成功获取
3、result:表示接口是否处理成功
code 错误码
msg 错误码对应的描述
data 接口返回的数据
APP接口输出格式
APP接口输出格式三要素:
code:错误码
msg:错误码对应的描述
data:接口返回的数据
App接口封装Json格式输出,也可以是使用类继承
APP接口输出格式三要素
trait实现代码复用,因为php是单继承语言,在想定义一些其他公共方法时候,可以使用这个方式来减少代码复用
封装截图及
trait 其实就是一个代码复用的类,但是他跟类不同的是:
trait 不能实例化,trait 只能 使用 use 进行引入
trait PHP5.4之后的代码复用机制
APP接口请求失败时的返回
public function jsonData($code,$message,$data=[])
{
return $this->jsonResponse($code,$message,$data);
}
APP接口请求成功时的返回
public function jsonSuccessData($data=[])
{
return $this->jsonResponse(code:0,message:'Success',$data);
}
返回一个json
trait ResponseJson
{
public function jsonResponse($code,$message,$data)
{
$content=[
'code'=>$code,
'msg'=>$message,
'data'=>$data,
];
return json_encode($content);
}
}
app接口输出格式三要素:
code 错误码
msg 错误码对应的描述
data 接口返回的数据
php trait是运用了组合的思想而不是继承的方式使用
示例——引用trait
示例——创建trait类
PHP trait [ 实现复用 ]