原文:http://www.upwqy.com/details/216.html
前面一个小项目中运用到的统一接口处理类使用起来很方便 http://www.upwqy.com/c-290.html
但是还有有不足之处 ,在model层 不能够直接进行断点 抛出异常,或者判断参数错误 直接返回。
在原来的基础上 我又做了一些调整
主要是兼容了。在model层可以直接抛出异常
代码如下
<?php
/**
* Created by PhpStorm.
* User: [一秋]
* Date: 2018/4/17
* Time: 14:44
* Desc: 成功源于点滴
*/
namespace app\lib\common;
//统一返回处理类
use think\Config;
use think\exception\HttpResponseException;
use think\Response;
class ServerResponse
{
//构造函数
private function __construct($status,$msg = "",$data = [])
{
$result['status'] = $status;
$msg ? $result['msg'] = $msg : null;
$data ? $result['data'] = $data : null;
$type = $this->getResponseType();
$header['Access-Control-Allow-Origin'] = '*';
$header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type';
$header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
$response = Response::create($result, $type)->header($header);
throw new HttpResponseException($response);
}
public static function createBySuccess($msg,$data = null){
return new ServerResponse(ResponseCode::SUCCESS,$msg,$data);
}
public static function createByError($msg){
return new ServerResponse(ResponseCode::ERROR,$msg);
}
/**
* 获取当前的response 输出类型
* @access protected
* @return string
*/
private function getResponseType()
{
return Config::get('default_return_type');
}
}
你也可以下载源码地址如下:http://www.upwqy.com/soft/check/11.html
使用示例:
控制器中
$res = UserModel::test();
dump($res);
return ServerResponse::createBySuccess("成功");
model类中
public static function test(){
ServerResponse::createByError("断点失败了");
return 1;
}
结果集
{
"status": 1,
"msg": "断点失败了"
}
可以看到在model中打的错误断点 直接抛出
但是这还不是最终想要的结果,我最近在学习java spring .在视频中 讲师 写了一结果处理类
ServerResponse 类 实现接口 Serializable 后 可以把类的对象属性在返回时 直接 以json格式进行了返回,具体的表述 可能和我说的不一致,
这样 还可以实现更多有用的功能。正在研究中。,上面的方法也可以直接使用
上一篇: Allowed memory size of 134217728 bytes exhausted (tried to allocate 54884479 bytes)
下一篇: 在linux修改文件夹及其子文件夹的权限