ホームページ  >  記事  >  PHPフレームワーク  >  Yii2 API インターフェース出力統合 Json および jsonp 形式メソッド

Yii2 API インターフェース出力統合 Json および jsonp 形式メソッド

angryTom
angryTom転載
2019-11-01 16:00:052458ブラウズ

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. 次に、送信前に処理を行う必要がありますが、処理のポイントは次のとおりです:

1>データの出力形式を変更する

2>デフォルトでは Json データが出力されます

3>リクエスト時にクライアントが $_GET['callback'] パラメータを渡す場合、出力は Jsonp 形式になります。

4>リクエストが正しい場合、データは { "success":true,"data":{.. .}}

5>エラー要求時のデータは {"success":false,"data":{"name":"Not Found ","message":"Page not found.","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输出
     * @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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はwww.yii-china.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。