如果做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('yii', 'An internal server error occurred.')); } $array = [ 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception', 'message' => $exception->getMessage(), 'code' => $exception->getCode(), ]; if ($exception instanceof HttpException) { $array['status'] = $exception->statusCode; } if (YII_DEBUG) { $array['type'] = get_class($exception); if (!$exception instanceof UserException) { $array['file'] = $exception->getFile(); $array['line'] = $exception->getLine(); $array['stack-trace'] = explode("\n", $exception->getTraceAsString()); if ($exception instanceof \yii\db\Exception) { $array['error-info'] = $exception->errorInfo; } } } if (($prev = $exception->getPrevious()) !== null) { $array['previous'] = $this->convertExceptionToArray($prev); } return $array; }
好了,這樣我們就有了標準同一個的api介面回傳資料格式了,在呼叫介面的人員也不用為了格式不統一感到煩惱
推薦:《Yii2.0框架開發實戰影片教學》
以上是Yii2 API介面輸出統一Json和jsonp格式方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!