如果做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格式方法的详细内容。