TP5封装一个API接口JSON返回类

文件名及存放目录

project —> extend —> Gucci —> ServerResponse.php

源码

<?php
/**
 * 统一返回处理类(ajax)允许跨域
 *
 * 使用: **
 *      use Gucci\ServerResponse;
 *      return ServerResponse::createBySuccess("成功");
 *      ServerResponse::createByError("断点失败了");
 */

namespace Gucci;

use think\facade\Config;
use think\exception\HttpResponseException;
use think\Response;

class ServerResponse
{
    public static $successCode = 1;
    public static $errorCode = 0;

    //构造函数
    public 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);
    }

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

    /**
     * 失败
     * @param $msg
     * @return ServerResponse
     */
    public static function createByError($msg){
        return new ServerResponse(self::$errorCode, $msg);

    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    private function getResponseType()
    {
        return Config::get('default_ajax_return');
    }
}
讨论数量: 1

echo 'Good!';

3个月前

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!