首页 >php框架 >YII >Yii2 API接口输出统一Json和jsonp格式方法

Yii2 API接口输出统一Json和jsonp格式方法

angryTom
angryTom转载
2019-11-01 16:00:052655浏览

Yii2 API接口输出统一Json和jsonp格式方法

如果做API的话,如何使别人再调用你的接口时能够有一个统一标准的json或者jsonp格式,然而 json响应的格式和内容,每个人的约定都是有差异的,所以我们必须再数据出去之前做一定的处理。 

1.首先我们需要初始化去调用beforeSend,因为我们需要对beforesend做一些处理,以下是init初始化处理代码:

/**
 * (non-PHPdoc)
 * @see \yii\base\Object::init()
 */
public function init()
{       
    parent::init();	//绑定beforeSend事件,更改数据输出格式
    Yii::$app->getResponse()->on(Response::EVENT_BEFORE_SEND, [$this, 'beforeSend']);
}

2.然后我们就需要对beforesend进行处理,处理点有下面几个重点: 

1>更改数据输出格式

2>默认情况下输出Json数据

3>如果客户端请求时有传递$_GET['callback']参数,输出Jsonp格式

4>请求正确时数据为 {"success":true,"data":{...}}

5>请求错误时数据为 {"success":false,"data":{"name":"Not Found","message":"页面未找到。","code":0,"status":404}} 

6>具体代码如下:

/**
     * 更改数据输出格式
     * 默认情况下输出Json数据
     * 如果客户端请求时有传递$_GET['callback']参数,输入Jsonp格式
     * 请求正确时数据为  {"success":true,"data":{...}}
     * 请求错误时数据为  {"success":false,"data":{"name":"Not Found","message":"页面未找到。","code":0,"status":404}}
     * @param \yii\base\Event $event
     */
    public function beforeSend($event)
    {        /* @var $response \yii\web\Response */
        $response = $event->sender;
        $isSuccessful = $response->isSuccessful;        if ($response->statusCode>=400) {            //异常处理
            if (true && $exception = Yii::$app->getErrorHandler()->exception) {
                $response->data = $this->convertExceptionToArray($exception);
            }            //Model出错了
            if ($response->statusCode==422) {
                $messages=[];                foreach ($response->data as $v) {
                    $messages[] = $v['message'];
                }                //请求错误时数据为  {"success":false,"data":{"name":"Not Found","message":"页面未找到。","code":0,"status":404}}
                $response->data = [                    'name'=> 'valide error',                    'message'=> implode("  ", $messages),                    'info'=>$response->data
                ];
            }
            $response->statusCode = 200;
        }        elseif ($response->statusCode>=300) {
            $response->statusCode = 200;
            $response->data = $this->convertExceptionToArray(new ForbiddenHttpException(Yii::t('yii', 'Login Required')));
        }        //请求正确时数据为  {"success":true,"data":{...}}
        $response->data = [            'success' => $isSuccessful,            'data' => $response->data,
        ];
        $response->format = Response::FORMAT_JSON;
        \Yii::$app->getResponse()->getHeaders()->set('Access-Control-Allow-Origin', '*');
        \Yii::$app->getResponse()->getHeaders()->set('Access-Control-Allow-Credentials', 'true');       //jsonp 格式输出
        if (isset($_GET['callback'])) {
            $response->format = Response::FORMAT_JSONP;
            $response->data = [                'callback' => $_GET['callback'],                'data'=>$response->data,
            ];
        }
    }

3.针对请求可能会发生一些异常,同样我们也需要对异常进行一些标准化处理,将异常转换为array输出,具体代码如下:

/**
     * 将异常转换为array输出
     * @see \yii\web\ErrorHandle
     * @param \Exception $exception
     * @return multitype:string NULL Ambigous <string, \yii\base\string> \yii\web\integer \yii\db\array multitype:string NULL Ambigous <string, \yii\base\string> \yii\web\integer \yii\db\array
     */
    protected function convertExceptionToArray($exception)
    {        if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) {
            $exception = new HttpException(500, Yii::t(&#39;yii&#39;, &#39;An internal server error occurred.&#39;));
        }
        $array = [            &#39;name&#39; => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : &#39;Exception&#39;,            &#39;message&#39; => $exception->getMessage(),            &#39;code&#39; => $exception->getCode(),
        ];        if ($exception instanceof HttpException) {
            $array[&#39;status&#39;] = $exception->statusCode;
        }        if (YII_DEBUG) {
            $array[&#39;type&#39;] = get_class($exception);            if (!$exception instanceof UserException) {
                $array[&#39;file&#39;] = $exception->getFile();
                $array[&#39;line&#39;] = $exception->getLine();
                $array[&#39;stack-trace&#39;] = explode("\n", $exception->getTraceAsString());                if ($exception instanceof \yii\db\Exception) {
                    $array[&#39;error-info&#39;] = $exception->errorInfo;
                }
            }
        }        if (($prev = $exception->getPrevious()) !== null) {
            $array[&#39;previous&#39;] = $this->convertExceptionToArray($prev);
        }        return $array;
    }

好了,这样我们就有了标准同一个的api接口返回数据格式了,在调用接口的人员也不用为了格式不统一感到烦恼

推荐:《Yii2.0框架开发实战视频教程

以上是Yii2 API接口输出统一Json和jsonp格式方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:www.yii-china.com。如有侵权,请联系admin@php.cn删除