格式化響應(yīng)(Response Formatting)

2018-02-24 15:40 更新

響應(yīng)格式

當(dāng)處理一個(gè) RESTful API 請(qǐng)求時(shí), 一個(gè)應(yīng)用程序通常需要如下步驟 來處理響應(yīng)格式:

  1. 確定可能影響響應(yīng)格式的各種因素, 例如媒介類型, 語言, 版本, 等等。 這個(gè)過程也被稱為?content negotiation。
  2. 資源對(duì)象轉(zhuǎn)換為數(shù)組, 如在?Resources?部分中所描述的。 通過 yii\rest\Serializer 來完成。
  3. 通過內(nèi)容協(xié)商步驟將數(shù)組轉(zhuǎn)換成字符串。 [yii\web\ResponseFormatterInterface|response formatters]] 通過 [yii\web\Response::formatters|response]] 應(yīng)用程序組件來注冊(cè)完成。

內(nèi)容協(xié)商

Yii 提供了通過 yii\filters\ContentNegotiator 過濾器支持內(nèi)容協(xié)商。RESTful API 基于 控制器類 yii\rest\Controller 在contentNegotiator?下配備這個(gè)過濾器。 文件管理器提供了涉及的響應(yīng)格式和語言。 例如, 如果一個(gè) RESTful API 請(qǐng)求中包含以下 header,

Accept: application/json; q=1.0, */*; q=0.1

將會(huì)得到JSON格式的響應(yīng),如下:

$ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users"

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By: PHP/5.4.20
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
      <http://localhost/users?page=2>; rel=next,
      <http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

[
    {
        "id": 1,
        ...
    },
    {
        "id": 2,
        ...
    },
    ...
]

幕后,執(zhí)行一個(gè) RESTful API 控制器動(dòng)作之前,yii\filters\ContentNegotiator filter 將檢查?Accept?HTTP header 在請(qǐng)求時(shí)和配置 yii\web\Response::format 為?'json'。 之后的動(dòng)作被執(zhí)行并返回得到的資源對(duì)象或集合, yii\rest\Serializer 將結(jié)果轉(zhuǎn)換成一個(gè)數(shù)組。最后,yii\web\JsonResponseFormatter 該數(shù)組將序列化為JSON字符串,并將其包括在響應(yīng)主體。

默認(rèn), RESTful APIs 同時(shí)支持JSON和XML格式。為了支持新的格式,你應(yīng)該 在?contentNegotiator?過濾器中配置 yii\filters\ContentNegotiator::formats 屬性, 類似如下 API 控制器類:

use yii\web\Response;

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_HTML;
    return $behaviors;
}

formats?屬性的keys支持 MIME 類型,而 values 必須在 yii\web\Response::formatters 中支持被響應(yīng)格式名稱。

數(shù)據(jù)序列化

正如我們上面所描述的,yii\rest\Serializer 負(fù)責(zé)轉(zhuǎn)換資源的中間件 對(duì)象或集合到數(shù)組。它將對(duì)象 yii\base\ArrayableInterface 作為 yii\data\DataProviderInterface。 前者主要由資源對(duì)象實(shí)現(xiàn), 而 后者是資源集合。

你可以通過設(shè)置 yii\rest\Controller::serializer 屬性和一個(gè)配置數(shù)組。 例如,有時(shí)你可能想通過直接在響應(yīng)主體內(nèi)包含分頁信息來 簡化客戶端的開發(fā)工作。這樣做,按照如下規(guī)則配置 yii\rest\Serializer::collectionEnvelope 屬性:

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];
}

那么你的請(qǐng)求可能會(huì)得到的響應(yīng)如下?http://localhost/users:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By: PHP/5.4.20
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
      <http://localhost/users?page=2>; rel=next,
      <http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "items": [
        {
            "id": 1,
            ...
        },
        {
            "id": 2,
            ...
        },
        ...
    ],
    "_links": {
        "self": {
            "href": "http://localhost/users?page=1"
        },
        "next": {
            "href": "http://localhost/users?page=2"
        },
        "last": {
            "href": "http://localhost/users?page=50"
        }
    },
    "_meta": {
        "totalCount": 1000,
        "pageCount": 50,
        "currentPage": 1,
        "perPage": 20
    }
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)