# 資源
RESTful 的 API 都是關于訪問和操作?*資源*,可將資源看成MVC模式中的?[模型](http://www.yiichina.com/doc/guide/2.0/structure-models)
在如何代表一個資源沒有固定的限定,在Yii中通常使用 yii\base\Model 或它的子類(如 yii\db\ActiveRecord) 代表資源,是為以下原因:
* yii\base\Model 實現了 yii\base\Arrayable 接口,它允許你通過RESTful API自定義你想要公開的資源數據。
* yii\base\Model 支持?[輸入驗證](http://www.yiichina.com/doc/guide/2.0/input-validation), 在你的RESTful API需要支持數據輸入時非常有用。
* yii\db\ActiveRecord 提供了強大的數據庫訪問和操作方面的支持,如資源數據需要存到數據庫它提供了完美的支持。
本節主要描述資源類如何從 yii\base\Model (或它的子類) 繼承并指定哪些數據可通過RESTful API返回,如果資源類沒有 繼承 yii\base\Model 會將它所有的公開成員變量返回。
## 字段
當RESTful API響應中包含一個資源時,該資源需要序列化成一個字符串。 Yii將這個過程分成兩步,首先,資源會被yii\rest\Serializer轉換成數組, 然后,該數組會通過yii\web\ResponseFormatterInterface根據請求格式(如JSON, XML)被序列化成字符串。 當開發一個資源類時應重點關注第一步。
通過覆蓋 yii\base\Model::fields() 和/或 yii\base\Model::extraFields() 方法, 可指定資源中稱為?*字段*?的數據放入展現數組中,兩個方法的差別為前者指定默認包含到展現數組的字段集合, 后者指定由于終端用戶的請求包含?`expand`?參數哪些額外的字段應被包含到展現數組,例如,
~~~
// 返回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() 默認返回模型的所有屬性作為字段, yii\db\ActiveRecord::fields() 只返回和數據表關聯的屬性作為字段。
可覆蓋?`fields()`?方法來增加、刪除、重命名、重定義字段,`fields()`?的返回值應為數組,數組的鍵為字段名 數組的值為對應的字段定義,可為屬性名或返回對應的字段值的匿名函數,特殊情況下,如果字段名和屬性名相同, 可省略數組的鍵,例如
~~~
// 明確列出每個字段,適用于你希望數據表或模型屬性修改時不導致你的字段修改(保持后端API兼容性)
public function fields()
{
return [
// 字段名和屬性名相同
'id',
// 字段名為"email", 對應的屬性名為"email_address"
'email' => 'email_address',
// 字段名為"name", 值由一個PHP回調函數定義
'name' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
];
}
// 過濾掉一些字段,適用于你希望繼承父類實現同時你想屏蔽掉一些敏感字段
public function fields()
{
$fields = parent::fields();
// 刪除一些包含敏感信息的字段
unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);
return $fields;
}
~~~
> 警告: 模型的所有屬性默認會被包含到API結果中,應檢查數據確保沒包含敏感數據,如果有敏感數據, 應覆蓋`fields()`過濾掉,在上述例子中,我們選擇過濾掉?`auth_key`,?`password_hash`?和?`password_reset_token`.
### 覆蓋?`extraFields()`?方法
yii\base\Model::extraFields() 默認返回空值,yii\db\ActiveRecord::extraFields() 返回和數據表關聯的屬性。
`extraFields()`?返回的數據格式和?`fields()`?相同,一般`extraFields()`?主要用于指定哪些值為對象的字段, 例如,給定以下字段申明
~~~
public function fields()
{
return ['id', 'email'];
}
public function extraFields()
{
return ['profile'];
}
~~~
`http://localhost/users?fields=id,email&expand=profile`?的請求可能返回如下JSON 數據:
~~~
[
{
"id": 100,
"email": "100@example.com",
"profile": {
"id": 100,
"age": 30,
}
},
...
]
~~~
## 鏈接
[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), 是Hypermedia as the Engine of Application State的縮寫, 提升RESTful API 應返回允許終端用戶訪問的資源操作的信息,HATEOAS 的目的是在API中返回包含相關鏈接信息的資源數據。
資源類通過實現yii\web\Linkable 接口來支持HATEOAS,該接口包含方法 yii\web\Linkable::getLinks() 來返回 yii\web\Link 列表,典型情況下應返回包含代表本資源對象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),
];
}
}
~~~
當響應中返回一個`User`?對象,它會包含一個?`_links`?單元表示和用戶相關的鏈接,例如
~~~
{
"id": 100,
"email": "user@example.com",
// ...
"_links" => {
"self": {
"href": "https://example.com/users/100"
}
}
}
~~~
## 集合
資源對象可以組成?*集合*,每個集合包含一組相同類型的資源對象。
集合可被展現成數組,更多情況下展現成?[data providers](http://www.yiichina.com/doc/guide/2.0/output-data-providers). 因為data providers支持資源的排序和分頁,這個特性在 RESTful API 返回集合時也用到,例如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(),
]);
}
}
~~~
當在RESTful API響應中發送data provider 時, yii\rest\Serializer 會取出資源的當前頁并組裝成資源對象數組, yii\rest\Serializer 也通過如下HTTP頭包含頁碼信息:
* `X-Pagination-Total-Count`: 資源所有數量;
* `X-Pagination-Page-Count`: 頁數;
* `X-Pagination-Current-Page`: 當前頁(從1開始);
* `X-Pagination-Per-Page`: 每頁資源數量;
* `Link`: 允許客戶端一頁一頁遍歷資源的導航鏈接集合.
可在[快速入門](http://www.yiichina.com/doc/guide/2.0/rest-quick-start#trying-it-out)?一節中找到樣例.
- 介紹(Introduction)
- 關于 Yii(About Yii)
- 從 Yii 1.1 升級(Upgrading from Version 1.1)
- 入門(Getting Started)
- 安裝 Yii(Installing Yii)
- 運行應用(Running Applications)
- 第一次問候(Saying Hello)
- 使用 Forms(Working with Forms)
- 玩轉 Databases(Working with Databases)
- 用 Gii 生成代碼(Generating Code with Gii)
- 更上一層樓(Looking Ahead)
- 應用結構(Application Structure)
- 結構概述(Overview)
- 入口腳本(Entry Scripts)
- 應用(Applications)
- 應用組件(Application Components)
- 控制器(Controllers)
- 模型(Models)
- 視圖(Views)
- 模塊(Modules)
- 過濾器(Filters)
- 小部件(Widgets)
- 前端資源(Assets)
- 擴展(Extensions)
- 請求處理(Handling Requests)
- 運行概述(Overview)
- 引導(Bootstrapping)
- 路由引導與創建 URL(Routing and URL Creation)
- 請求(Requests)
- 響應(Responses)
- Sessions and Cookies
- 錯誤處理(Handling Errors)
- 日志(Logging)
- 關鍵概念(Key Concepts)
- 組件(Components)
- 屬性(Properties)
- 事件(Events)
- 行為(Behaviors)
- 配置(Configurations)
- 別名(Aliases)
- 類自動加載(Class Autoloading)
- 服務定位器(Service Locator)
- 依賴注入容器(Dependency Injection Container)
- 配合數據庫工作(Working with Databases)
- 數據庫訪問(Data Access Objects): 數據庫連接、基本查詢、事務和模式操作
- 查詢生成器(Query Builder): 使用簡單抽象層查詢數據庫
- 活動記錄(Active Record): 活動記錄對象關系映射(ORM),檢索和操作記錄、定義關聯關系
- 數據庫遷移(Migrations): 在團體開發中對你的數據庫使用版本控制
- Sphinx
- Redis
- MongoDB
- ElasticSearch
- 接收用戶數據(Getting Data from Users)
- 創建表單(Creating Forms)
- 輸入驗證(Validating Input)
- 文件上傳(Uploading Files)
- 收集列表輸入(Collecting Tabular Input)
- 多模型同時輸入(Getting Data for Multiple Models)
- 顯示數據(Displaying Data)
- 格式化輸出數據(Data Formatting)
- 分頁(Pagination)
- 排序(Sorting)
- 數據提供器(Data Providers)
- 數據小部件(Data Widgets)
- 操作客戶端腳本(Working with Client Scripts)
- 主題(Theming)
- 安全(Security)
- 認證(Authentication)
- 授權(Authorization)
- 處理密碼(Working with Passwords)
- 客戶端認證(Auth Clients)
- 安全領域的最佳實踐(Best Practices)
- 緩存(Caching)
- 概述(Overview)
- 數據緩存(Data Caching)
- 片段緩存(Fragment Caching)
- 分頁緩存(Page Caching)
- HTTP 緩存(HTTP Caching)
- RESTful Web 服務
- 快速入門(Quick Start)
- 資源(Resources)
- 控制器(Controllers)
- 路由(Routing)
- 格式化響應(Response Formatting)
- 授權驗證(Authentication)
- 速率限制(Rate Limiting)
- 版本化(Versioning)
- 錯誤處理(Error Handling)
- 開發工具(Development Tools)
- 調試工具欄和調試器(Debug Toolbar and Debugger)
- 使用 Gii 生成代碼(Generating Code using Gii)
- TBD 生成 API 文檔(Generating API Documentation)
- 測試(Testing)
- 概述(Overview)
- 搭建測試環境(Testing environment setup)
- 單元測試(Unit Tests)
- 功能測試(Functional Tests)
- 驗收測試(Acceptance Tests)
- 測試夾具(Fixtures)
- 高級專題(Special Topics)
- 高級應用模版(Advanced Project Template)
- 從頭構建自定義模版(Building Application from Scratch)
- 控制臺命令(Console Commands)
- 核心驗證器(Core Validators)
- 國際化(Internationalization)
- 收發郵件(Mailing)
- 性能優化(Performance Tuning)
- 共享主機環境(Shared Hosting Environment)
- 模板引擎(Template Engines)
- 集成第三方代碼(Working with Third-Party Code)
- 小部件(Widgets)
- Bootstrap 小部件(Bootstrap Widgets)
- jQuery UI 小部件(jQuery UI Widgets)
- 助手類(Helpers)
- 助手一覽(Overview)
- Array 助手(ArrayHelper)
- Html 助手(Html)
- Url 助手(Url)