資源(Resources)

2018-02-24 15:40 更新

資源

RESTful 的 API 都是關(guān)于訪(fǎng)問(wèn)和操作?資源,可將資源看成MVC模式中的?模型

在如何代表一個(gè)資源沒(méi)有固定的限定,在Yii中通常使用 yii\base\Model 或它的子類(lèi)(如 yii\db\ActiveRecord) 代表資源,是為以下原因:

  • yii\base\Model 實(shí)現(xiàn)了 yii\base\Arrayable 接口,它允許你通過(guò)RESTful API自定義你想要公開(kāi)的資源數(shù)據(jù)。
  • yii\base\Model 支持?輸入驗(yàn)證, 在你的RESTful API需要支持?jǐn)?shù)據(jù)輸入時(shí)非常有用。
  • yii\db\ActiveRecord 提供了強(qiáng)大的數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)和操作方面的支持,如資源數(shù)據(jù)需要存到數(shù)據(jù)庫(kù)它提供了完美的支持。

本節(jié)主要描述資源類(lèi)如何從 yii\base\Model (或它的子類(lèi)) 繼承并指定哪些數(shù)據(jù)可通過(guò)RESTful API返回,如果資源類(lèi)沒(méi)有 繼承 yii\base\Model 會(huì)將它所有的公開(kāi)成員變量返回。

字段

當(dāng)RESTful API響應(yīng)中包含一個(gè)資源時(shí),該資源需要序列化成一個(gè)字符串。 Yii將這個(gè)過(guò)程分成兩步,首先,資源會(huì)被yii\rest\Serializer轉(zhuǎn)換成數(shù)組, 然后,該數(shù)組會(huì)通過(guò)yii\web\ResponseFormatterInterface根據(jù)請(qǐng)求格式(如JSON, XML)被序列化成字符串。 當(dāng)開(kāi)發(fā)一個(gè)資源類(lèi)時(shí)應(yīng)重點(diǎn)關(guān)注第一步。

通過(guò)覆蓋 yii\base\Model::fields() 和/或 yii\base\Model::extraFields() 方法, 可指定資源中稱(chēng)為?字段?的數(shù)據(jù)放入展現(xiàn)數(shù)組中,兩個(gè)方法的差別為前者指定默認(rèn)包含到展現(xiàn)數(shù)組的字段集合, 后者指定由于終端用戶(hù)的請(qǐng)求包含?expand?參數(shù)哪些額外的字段應(yīng)被包含到展現(xiàn)數(shù)組,例如,

// 返回fields()方法中申明的所有字段
http://localhost/users

// 只返回fields()方法中申明的id和email字段
http://localhost/users?fields=id,email

// 返回fields()方法申明的所有字段,以及extraFields()方法中的profile字段
http://localhost/users?expand=profile

// 返回回fields()和extraFields()方法中提供的id, email 和 profile字段
http://localhost/users?fields=id,email&expand=profile

覆蓋?fields()?方法

yii\base\Model::fields() 默認(rèn)返回模型的所有屬性作為字段, yii\db\ActiveRecord::fields() 只返回和數(shù)據(jù)表關(guān)聯(lián)的屬性作為字段。

可覆蓋?fields()?方法來(lái)增加、刪除、重命名、重定義字段,fields()?的返回值應(yīng)為數(shù)組,數(shù)組的鍵為字段名 數(shù)組的值為對(duì)應(yīng)的字段定義,可為屬性名或返回對(duì)應(yīng)的字段值的匿名函數(shù),特殊情況下,如果字段名和屬性名相同, 可省略數(shù)組的鍵,例如

// 明確列出每個(gè)字段,適用于你希望數(shù)據(jù)表或模型屬性修改時(shí)不導(dǎo)致你的字段修改(保持后端API兼容性)
public function fields()
{
    return [
        // 字段名和屬性名相同
        'id',
        // 字段名為"email", 對(duì)應(yīng)的屬性名為"email_address"
        'email' => 'email_address',
        // 字段名為"name", 值由一個(gè)PHP回調(diào)函數(shù)定義
        'name' => function ($model) {
            return $model->first_name . ' ' . $model->last_name;
        },
    ];
}

// 過(guò)濾掉一些字段,適用于你希望繼承父類(lèi)實(shí)現(xiàn)同時(shí)你想屏蔽掉一些敏感字段
public function fields()
{
    $fields = parent::fields();

    // 刪除一些包含敏感信息的字段
    unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);

    return $fields;
}

警告: 模型的所有屬性默認(rèn)會(huì)被包含到API結(jié)果中,應(yīng)檢查數(shù)據(jù)確保沒(méi)包含敏感數(shù)據(jù),如果有敏感數(shù)據(jù), 應(yīng)覆蓋fields()過(guò)濾掉,在上述例子中,我們選擇過(guò)濾掉?auth_key,?password_hash?和?password_reset_token.

覆蓋?extraFields()?方法

yii\base\Model::extraFields() 默認(rèn)返回空值,yii\db\ActiveRecord::extraFields() 返回和數(shù)據(jù)表關(guān)聯(lián)的屬性。

extraFields()?返回的數(shù)據(jù)格式和?fields()?相同,一般extraFields()?主要用于指定哪些值為對(duì)象的字段, 例如,給定以下字段申明

public function fields()
{
    return ['id', 'email'];
}

public function extraFields()
{
    return ['profile'];
}

http://localhost/users?fields=id,email&expand=profile?的請(qǐng)求可能返回如下JSON 數(shù)據(jù):

[
    {
        "id": 100,
        "email": "100@example.com",
        "profile": {
            "id": 100,
            "age": 30,
        }
    },
    ...
]

鏈接

HATEOAS, 是Hypermedia as the Engine of Application State的縮寫(xiě), 提升RESTful API 應(yīng)返回允許終端用戶(hù)訪(fǎng)問(wèn)的資源操作的信息,HATEOAS 的目的是在API中返回包含相關(guān)鏈接信息的資源數(shù)據(jù)。

資源類(lèi)通過(guò)實(shí)現(xiàn)yii\web\Linkable 接口來(lái)支持HATEOAS,該接口包含方法 yii\web\Linkable::getLinks() 來(lái)返回 yii\web\Link 列表,典型情況下應(yīng)返回包含代表本資源對(duì)象URL的?self?鏈接,例如

use yii\db\ActiveRecord;
use yii\web\Link;
use yii\web\Linkable;
use yii\helpers\Url;

class User extends ActiveRecord implements Linkable
{
    public function getLinks()
    {
        return [
            Link::REL_SELF => Url::to(['user/view', 'id' => $this->id], true),
        ];
    }
}

當(dāng)響應(yīng)中返回一個(gè)User?對(duì)象,它會(huì)包含一個(gè)?_links?單元表示和用戶(hù)相關(guān)的鏈接,例如

{
    "id": 100,
    "email": "user@example.com",
    // ...
    "_links" => {
        "self": {
            "href": "https://example.com/users/100"
        }
    }
}

集合

資源對(duì)象可以組成?集合,每個(gè)集合包含一組相同類(lèi)型的資源對(duì)象。

集合可被展現(xiàn)成數(shù)組,更多情況下展現(xiàn)成?data providers. 因?yàn)閐ata providers支持資源的排序和分頁(yè),這個(gè)特性在 RESTful API 返回集合時(shí)也用到,例如This is because data providers support sorting and pagination 如下操作返回post資源的data provider:

namespace app\controllers;

use yii\rest\Controller;
use yii\data\ActiveDataProvider;
use app\models\Post;

class PostController extends Controller
{
    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => Post::find(),
        ]);
    }
}

當(dāng)在RESTful API響應(yīng)中發(fā)送data provider 時(shí), yii\rest\Serializer 會(huì)取出資源的當(dāng)前頁(yè)并組裝成資源對(duì)象數(shù)組, yii\rest\Serializer 也通過(guò)如下HTTP頭包含頁(yè)碼信息:

  • X-Pagination-Total-Count: 資源所有數(shù)量;
  • X-Pagination-Page-Count: 頁(yè)數(shù);
  • X-Pagination-Current-Page: 當(dāng)前頁(yè)(從1開(kāi)始);
  • X-Pagination-Per-Page: 每頁(yè)資源數(shù)量;
  • Link: 允許客戶(hù)端一頁(yè)一頁(yè)遍歷資源的導(dǎo)航鏈接集合.

可在快速入門(mén)?一節(jié)中找到樣例.

以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)