API接口通用返回类,TP通用


/**
 * API接口返回类
 */

namespace app\admin\controller;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class ApiResponse
{
    public static $successCode = 200;
    public static $errorCode = 400;

    //构造函数
    private function __construct( $code = 0, $msg = "",  $data = [], array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];

        $type  = $this->getResponseType();
        $response   = Response::create($result, $type)->header($header);
        throw  new HttpResponseException($response);
    }

    /**
     * 返回成功
     * @param $msg
     * @param null $data
     * @return ApiResponse
     */
    public static function success($msg , $data = null){
        return new ApiResponse(self::$successCode,$msg,$data);
    }

    /**
     * 返回错误
     * @param $msg
     * @return ApiResponse
     */
    public static function error($msg){
        return new ApiResponse(self::$errorCode,$msg);

    }
    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    private function getResponseType()
    {
        return config('default_ajax_return');//json
    }
}

注意:default_ajax_return = “json”,在模版中渲染需要用这个函数 return view(‘menu/index’);不能用 return $this->fetch();

以上不考虑跨域访问,如果有跨域问题可以设定header头部,在构造函数中添加:

 $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';

你可能感兴趣的:(API接口通用返回类,TP通用)