tp5 api接口 统一结果返回处理类

浏览:6640 发布日期:2018/04/17 分类:技术分享 关键字: tp5 api 接口
前面一个小项目中运用到的统一接口处理类使用起来很方便 http://www.upwqy.com/c-290.html

但是还有有不足之处 ,在model层 不能够直接进行断点 抛出异常,或者判断参数错误 直接返回。

在原来的基础上 我又做了一些调整
主要是兼容了。在model层可以直接抛出异常
原来链接 http://www.upwqy.com/details/216.html
你也可以下载源码.这里提供了下载地址:http://www.upwqy.com/soft/check/11.html<?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');
    }

}
最佳答案
评论( 相关
后面还有条评论,点击查看>>