From bd47b3db4e8d881eb508f6318760fb12471c9934 Mon Sep 17 00:00:00 2001 From: BOB CHENGBIN Date: Thu, 4 Dec 2014 15:45:54 +0800 Subject: [PATCH 01/11] =?UTF-8?q?=E4=BF=AE=E6=AD=A3Sphinx=E5=8D=95?= =?UTF-8?q?=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/guide-zh-CN/db-active-record.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide-zh-CN/db-active-record.md b/docs/guide-zh-CN/db-active-record.md index 18ff81b82e..a327dafa3a 100644 --- a/docs/guide-zh-CN/db-active-record.md +++ b/docs/guide-zh-CN/db-active-record.md @@ -37,7 +37,7 @@ $db->createCommand('INSERT INTO customer (name) VALUES (:name)', [ * Microsoft SQL Server 2010 及以上:通过 [[yii\db\ActiveRecord]] * Oracle: 通过 [[yii\db\ActiveRecord]] * CUBRID 9.1 及以上:通过 [[yii\db\ActiveRecord]] -* Sphnix:通过 [[yii\sphinx\ActiveRecord]],需求 `yii2-sphinx` 扩展 +* Sphinx:通过 [[yii\sphinx\ActiveRecord]],需求 `yii2-sphinx` 扩展 * ElasticSearch:通过 [[yii\elasticsearch\ActiveRecord]],需求 `yii2-elasticsearch` 扩展 * Redis 2.6.12 及以上:通过 [[yii\redis\ActiveRecord]],需求 `yii2-redis` 扩展 * MongoDB 1.3.0 及以上:通过 [[yii\mongodb\ActiveRecord]],需求 `yii2-mongodb` 扩展 @@ -1004,4 +1004,4 @@ TODO ------------------- - [模型(Model)](model.md) -- [[yii\db\ActiveRecord]] \ No newline at end of file +- [[yii\db\ActiveRecord]] From d51dcd94322b0528990eff667a6a9b891cd9f78e Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Sat, 20 Dec 2014 17:39:20 +0800 Subject: [PATCH 02/11] initial english --- docs/guide-zh-CN/rest-resources.md | 218 +++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 docs/guide-zh-CN/rest-resources.md diff --git a/docs/guide-zh-CN/rest-resources.md b/docs/guide-zh-CN/rest-resources.md new file mode 100644 index 0000000000..37a470587a --- /dev/null +++ b/docs/guide-zh-CN/rest-resources.md @@ -0,0 +1,218 @@ +Resources +========= + +RESTful APIs are all about accessing and manipulating *resources*. You may view resources as +[models](structure-models.md) in the MVC paradigm. + +While there is no restriction in how to represent a resource, in Yii you usually would represent resources +in terms of objects of [[yii\base\Model]] or its child classes (e.g. [[yii\db\ActiveRecord]]), for the +following reasons: + +* [[yii\base\Model]] implements the [[yii\base\Arrayable]] interface, which allows you to + customize how you want to expose resource data through RESTful APIs. +* [[yii\base\Model]] supports [input validation](input-validation.md), which is useful if your RESTful APIs + need to support data input. +* [[yii\db\ActiveRecord]] provides powerful DB data access and manipulation support, which makes it + a perfect fit if your resource data is stored in databases. + +In this section, we will mainly describe how a resource class extending from [[yii\base\Model]] (or its child classes) +can specify what data may be returned via RESTful APIs. If the resource class does not extend from [[yii\base\Model]], +then all its public member variables will be returned. + + +## Fields + +When including a resource in a RESTful API response, the resource needs to be serialized into a string. +Yii breaks this process into two steps. First, the resource is converted into an array by [[yii\rest\Serializer]]. +Second, the array is serialized into a string in a requested format (e.g. JSON, XML) by +[[yii\web\ResponseFormatterInterface|response formatters]]. The first step is what you should mainly focus when +developing a resource class. + +By overriding [[yii\base\Model::fields()|fields()]] and/or [[yii\base\Model::extraFields()|extraFields()]], +you may specify what data, called *fields*, in the resource can be put into its array representation. +The difference between these two methods is that the former specifies the default set of fields which should +be included in the array representation, while the latter specifies additional fields which may be included +in the array if an end user requests for them via the `expand` query parameter. For example, + +``` +// returns all fields as declared in fields() +http://localhost/users + +// only returns field id and email, provided they are declared in fields() +http://localhost/users?fields=id,email + +// returns all fields in fields() and field profile if it is in extraFields() +http://localhost/users?expand=profile + +// only returns field id, email and profile, provided they are in fields() and extraFields() +http://localhost/users?fields=id,email&expand=profile +``` + + +### Overriding `fields()` + +By default, [[yii\base\Model::fields()]] returns all model attributes as fields, while +[[yii\db\ActiveRecord::fields()]] only returns the attributes which have been populated from DB. + +You can override `fields()` to add, remove, rename or redefine fields. The return value of `fields()` +should be an array. The array keys are the field names, and the array values are the corresponding +field definitions which can be either property/attribute names or anonymous functions returning the +corresponding field values. In the special case when a field name is the same as its defining attribute +name, you can omit the array key. For example, + +```php +// explicitly list every field, best used when you want to make sure the changes +// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility). +public function fields() +{ + return [ + // field name is the same as the attribute name + 'id', + // field name is "email", the corresponding attribute name is "email_address" + 'email' => 'email_address', + // field name is "name", its value is defined by a PHP callback + 'name' => function ($model) { + return $model->first_name . ' ' . $model->last_name; + }, + ]; +} + +// filter out some fields, best used when you want to inherit the parent implementation +// and blacklist some sensitive fields. +public function fields() +{ + $fields = parent::fields(); + + // remove fields that contain sensitive information + unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']); + + return $fields; +} +``` + +> Warning: Because by default all attributes of a model will be included in the API result, you should +> examine your data to make sure they do not contain sensitive information. If there is such information, +> you should override `fields()` to filter them out. In the above example, we choose +> to filter out `auth_key`, `password_hash` and `password_reset_token`. + + +### Overriding `extraFields()` + +By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]] +returns the names of the relations that have been populated from DB. + +The return data format of `extraFields()` is the same as that of `fields()`. Usually, `extraFields()` +is mainly used to specify fields whose values are objects. For example, given the following field +declaration, + +```php +public function fields() +{ + return ['id', 'email']; +} + +public function extraFields() +{ + return ['profile']; +} +``` + +the request with `http://localhost/users?fields=id,email&expand=profile` may return the following JSON data: + +```php +[ + { + "id": 100, + "email": "100@example.com", + "profile": { + "id": 100, + "age": 30, + } + }, + ... +] +``` + + +## Links + +[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), an abbreviation for Hypermedia as the Engine of Application State, +promotes that RESTful APIs should return information that allow clients to discover actions supported for the returned +resources. The key of HATEOAS is to return a set of hyperlinks with relation information when resource data are served +by the APIs. + +Your resource classes may support HATEOAS by implementing the [[yii\web\Linkable]] interface. The interface +contains a single method [[yii\web\Linkable::getLinks()|getLinks()]] which should return a list of [[yii\web\Link|links]]. +Typically, you should return at least the `self` link representing the URL to the resource object itself. For example, + +```php +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), + ]; + } +} +``` + +When a `User` object is returned in a response, it will contain a `_links` element representing the links related +to the user, for example, + +``` +{ + "id": 100, + "email": "user@example.com", + // ... + "_links" => [ + "self": "https://example.com/users/100" + ] +} +``` + + +## Collections + +Resource objects can be grouped into *collections*. Each collection contains a list of resource objects +of the same type. + +While collections can be represented as arrays, it is usually more desirable to represent them +as [data providers](output-data-providers.md). This is because data providers support sorting and pagination +of resources, which is a commonly needed feature for RESTful APIs returning collections. For example, +the following action returns a data provider about the post resources: + +```php +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(), + ]); + } +} +``` + +When a data provider is being sent in a RESTful API response, [[yii\rest\Serializer]] will take out the current +page of resources and serialize them as an array of resource objects. Additionally, [[yii\rest\Serializer]] +will also include the pagination information by the following HTTP headers: + +* `X-Pagination-Total-Count`: The total number of resources; +* `X-Pagination-Page-Count`: The number of pages; +* `X-Pagination-Current-Page`: The current page (1-based); +* `X-Pagination-Per-Page`: The number of resources in each page; +* `Link`: A set of navigational links allowing client to traverse the resources page by page. + +An example may be found in the [Quick Start](rest-quick-start.md#trying-it-out) section. From 6a71b5b3d96f83733f6c7e26f4bfe70a14d2944c Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Tue, 23 Dec 2014 17:57:17 +0800 Subject: [PATCH 03/11] for check --- docs/guide-zh-CN/rest-resources.md | 93 ++++++++++++++++++++++-------- 1 file changed, 70 insertions(+), 23 deletions(-) diff --git a/docs/guide-zh-CN/rest-resources.md b/docs/guide-zh-CN/rest-resources.md index 37a470587a..b7a9b34d52 100644 --- a/docs/guide-zh-CN/rest-resources.md +++ b/docs/guide-zh-CN/rest-resources.md @@ -1,38 +1,57 @@ Resources +资源 ========= RESTful APIs are all about accessing and manipulating *resources*. You may view resources as [models](structure-models.md) in the MVC paradigm. +RESTful 的 API 都是关于访问和操作 *资源*,可将资源看成MVC模式中的 +[模型](structure-models.md) While there is no restriction in how to represent a resource, in Yii you usually would represent resources in terms of objects of [[yii\base\Model]] or its child classes (e.g. [[yii\db\ActiveRecord]]), for the following reasons: +在如何代表一个资源没有固定的限定,在Yii中通常使用 [[yii\base\Model]] 或它的子类(如 [[yii\db\ActiveRecord]]) +代表资源,是为以下原因: * [[yii\base\Model]] implements the [[yii\base\Arrayable]] interface, which allows you to customize how you want to expose resource data through RESTful APIs. +* [[yii\base\Model]] 实现了 [[yii\base\Arrayable]] 接口,它允许你通过RESTful API自定义你想要公开的资源数据。 * [[yii\base\Model]] supports [input validation](input-validation.md), which is useful if your RESTful APIs need to support data input. +* [[yii\base\Model]] 支持 [输入验证](input-validation.md), 在你的RESTful API需要支持数据输入时非常有用。 * [[yii\db\ActiveRecord]] provides powerful DB data access and manipulation support, which makes it a perfect fit if your resource data is stored in databases. +* [[yii\db\ActiveRecord]] 提供了强大的数据库访问和操作方面的支持,如资源数据需要存到数据库它提供了完美的支持。 In this section, we will mainly describe how a resource class extending from [[yii\base\Model]] (or its child classes) can specify what data may be returned via RESTful APIs. If the resource class does not extend from [[yii\base\Model]], then all its public member variables will be returned. +本节主要描述资源类如何从 [[yii\base\Model]] (或它的子类) 继承并指定哪些数据可通过RESTful API返回,如果资源类没有 +继承 [[yii\base\Model]] 会将它所有的公开成员变量返回。 ## Fields +## 字段 When including a resource in a RESTful API response, the resource needs to be serialized into a string. Yii breaks this process into two steps. First, the resource is converted into an array by [[yii\rest\Serializer]]. Second, the array is serialized into a string in a requested format (e.g. JSON, XML) by [[yii\web\ResponseFormatterInterface|response formatters]]. The first step is what you should mainly focus when developing a resource class. +当RESTful API响应中包含一个资源时,该资源需要序列化成一个字符串。 +Yii将这个过程分成两步,首先,资源会被[[yii\rest\Serializer]]转换成数组, +然后,该数组会通过[[yii\web\ResponseFormatterInterface|response formatters]]根据请求格式(如JSON, XML)被序列化成字符串。 +当开发一个资源类时应重点关注第一步。 By overriding [[yii\base\Model::fields()|fields()]] and/or [[yii\base\Model::extraFields()|extraFields()]], you may specify what data, called *fields*, in the resource can be put into its array representation. The difference between these two methods is that the former specifies the default set of fields which should be included in the array representation, while the latter specifies additional fields which may be included in the array if an end user requests for them via the `expand` query parameter. For example, +通过覆盖 [[yii\base\Model::fields()|fields()]] 和/或 [[yii\base\Model::extraFields()|extraFields()]] 方法, +可指定资源中称为 *字段* 的数据放入展现数组中,两个方法的差别为前者指定默认包含到展现数组的字段集合, +后者指定由于终端用户的请求包含 `expand` 参数哪些额外的字段应被包含到展现数组,例如, + ``` // returns all fields as declared in fields() @@ -47,43 +66,60 @@ http://localhost/users?expand=profile // only returns field id, email and profile, provided they are in fields() and extraFields() http://localhost/users?fields=id,email&expand=profile ``` +``` +// 返回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 +``` ### Overriding `fields()` +### 覆盖 `fields()` 方法 By default, [[yii\base\Model::fields()]] returns all model attributes as fields, while [[yii\db\ActiveRecord::fields()]] only returns the attributes which have been populated from DB. +[[yii\base\Model::fields()]] 默认返回模型的所有属性作为字段, +[[yii\db\ActiveRecord::fields()]] 只返回和数据表关联的属性作为字段。 You can override `fields()` to add, remove, rename or redefine fields. The return value of `fields()` should be an array. The array keys are the field names, and the array values are the corresponding field definitions which can be either property/attribute names or anonymous functions returning the corresponding field values. In the special case when a field name is the same as its defining attribute name, you can omit the array key. For example, +可覆盖 `fields()` 方法来增加、删除、重命名、重定义字段,`fields()` 的返回值应为数组,数组的键为字段名 +数组的值为对应的字段定义,可为属性名或返回对应的字段值的匿名函数,特殊情况下,如果字段名和属性名相同, +可省略数组的键,例如 ```php -// explicitly list every field, best used when you want to make sure the changes -// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility). +// 明确列出每个字段,适用于你希望数据表或模型属性修改时不导致你的字段修改(保持后端API兼容性) public function fields() { return [ - // field name is the same as the attribute name + // 字段名和属性名相同 'id', - // field name is "email", the corresponding attribute name is "email_address" + // 字段名为"email", 对应的属性名为"email_address" 'email' => 'email_address', - // field name is "name", its value is defined by a PHP callback + // 字段名为"name", 值由一个PHP回调函数定义 'name' => function ($model) { return $model->first_name . ' ' . $model->last_name; }, ]; } -// filter out some fields, best used when you want to inherit the parent implementation -// and blacklist some sensitive fields. +// 过滤掉一些字段,适用于你希望继承父类实现同时你想屏蔽掉一些敏感字段 public function fields() { $fields = parent::fields(); - // remove fields that contain sensitive information + // 删除一些包含敏感信息的字段 unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']); return $fields; @@ -94,16 +130,22 @@ public function fields() > examine your data to make sure they do not contain sensitive information. If there is such information, > you should override `fields()` to filter them out. In the above example, we choose > to filter out `auth_key`, `password_hash` and `password_reset_token`. +> 警告: 模型的所有属性默认会被包含到API结果中,应检查数据确保没包含敏感数据,如果有敏感数据, +> 应覆盖`fields()`过滤掉,在上述例子中,我们选择过滤掉 `auth_key`, `password_hash` 和 `password_reset_token`. ### Overriding `extraFields()` +### 覆盖 `extraFields()` 方法 By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]] returns the names of the relations that have been populated from DB. +[[yii\base\Model::extraFields()]] 默认返回空值,[[yii\db\ActiveRecord::extraFields()]] 返回和数据表关联的属性。 The return data format of `extraFields()` is the same as that of `fields()`. Usually, `extraFields()` is mainly used to specify fields whose values are objects. For example, given the following field declaration, +`extraFields()` 返回的数据格式和 `fields()` 相同,一般`extraFields()` 主要用于指定哪些值为对象的字段, +例如,给定以下字段申明 ```php public function fields() @@ -117,7 +159,7 @@ public function extraFields() } ``` -the request with `http://localhost/users?fields=id,email&expand=profile` may return the following JSON data: +`http://localhost/users?fields=id,email&expand=profile` 的请求可能返回如下JSON 数据: ```php [ @@ -135,15 +177,13 @@ the request with `http://localhost/users?fields=id,email&expand=profile` may ret ## Links +## 链接 -[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), an abbreviation for Hypermedia as the Engine of Application State, -promotes that RESTful APIs should return information that allow clients to discover actions supported for the returned -resources. The key of HATEOAS is to return a set of hyperlinks with relation information when resource data are served -by the APIs. +[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), 是Hypermedia as the Engine of Application State的缩写, +提升RESTful API 应返回允许终端用户访问的资源操作的信息,HATEOAS 的目的是在API中返回包含相关链接信息的资源数据。 -Your resource classes may support HATEOAS by implementing the [[yii\web\Linkable]] interface. The interface -contains a single method [[yii\web\Linkable::getLinks()|getLinks()]] which should return a list of [[yii\web\Link|links]]. -Typically, you should return at least the `self` link representing the URL to the resource object itself. For example, +资源类通过实现[[yii\web\Linkable]] 接口来支持HATEOAS,该接口包含方法 [[yii\web\Linkable::getLinks()|getLinks()]] 来返回 +[[yii\web\Link|links]] 列表,典型情况下应返回包含代表本资源对象URL的 `self` 链接,例如 ```php use yii\db\ActiveRecord; @@ -162,8 +202,7 @@ class User extends ActiveRecord implements Linkable } ``` -When a `User` object is returned in a response, it will contain a `_links` element representing the links related -to the user, for example, +当响应中返回一个`User` 对象,它会包含一个 `_links` 单元表示和用户相关的链接,例如 ``` { @@ -178,14 +217,17 @@ to the user, for example, ## Collections +## 集合 -Resource objects can be grouped into *collections*. Each collection contains a list of resource objects -of the same type. +资源对象可以组成 *集合*,每个集合包含一组相同类型的资源对象。 While collections can be represented as arrays, it is usually more desirable to represent them as [data providers](output-data-providers.md). This is because data providers support sorting and pagination of resources, which is a commonly needed feature for RESTful APIs returning collections. For example, the following action returns a data provider about the post resources: +集合可被展现成数组,更多情况下展现成 [data providers](output-data-providers.md). +因为data providers支持资源的排序和分页,这个特性在 RESTful API 返回集合时也用到,例如This is because data providers support sorting and pagination +如下操作返回post资源的data provider: ```php namespace app\controllers; @@ -205,14 +247,19 @@ class PostController extends Controller } ``` -When a data provider is being sent in a RESTful API response, [[yii\rest\Serializer]] will take out the current -page of resources and serialize them as an array of resource objects. Additionally, [[yii\rest\Serializer]] -will also include the pagination information by the following HTTP headers: +当在RESTful API响应中发送data provider 时, [[yii\rest\Serializer]] 会取出资源的当前页并组装成资源对象数组, +[[yii\rest\Serializer]] 也通过如下HTTP头包含页码信息: * `X-Pagination-Total-Count`: The total number of resources; * `X-Pagination-Page-Count`: The number of pages; * `X-Pagination-Current-Page`: The current page (1-based); * `X-Pagination-Per-Page`: The number of resources in each page; * `Link`: A set of navigational links allowing client to traverse the resources page by page. +* `X-Pagination-Total-Count`: 资源所有数量; +* `X-Pagination-Page-Count`: 页数; +* `X-Pagination-Current-Page`: 当前页(从1开始); +* `X-Pagination-Per-Page`: 每页资源数量; +* `Link`: 允许客户端一页一页遍历资源的导航链接集合. An example may be found in the [Quick Start](rest-quick-start.md#trying-it-out) section. +可在[快速入门](rest-quick-start.md#trying-it-out) 一节中找到样例. From 6ae4e54b8254a9fd0f9b4e896815aafa7219b49d Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Tue, 23 Dec 2014 18:00:08 +0800 Subject: [PATCH 04/11] new chinese translation --- docs/guide-zh-CN/rest-resources.md | 69 ------------------------------ 1 file changed, 69 deletions(-) diff --git a/docs/guide-zh-CN/rest-resources.md b/docs/guide-zh-CN/rest-resources.md index b7a9b34d52..a3c01da363 100644 --- a/docs/guide-zh-CN/rest-resources.md +++ b/docs/guide-zh-CN/rest-resources.md @@ -1,71 +1,32 @@ -Resources 资源 ========= -RESTful APIs are all about accessing and manipulating *resources*. You may view resources as -[models](structure-models.md) in the MVC paradigm. RESTful 的 API 都是关于访问和操作 *资源*,可将资源看成MVC模式中的 [模型](structure-models.md) -While there is no restriction in how to represent a resource, in Yii you usually would represent resources -in terms of objects of [[yii\base\Model]] or its child classes (e.g. [[yii\db\ActiveRecord]]), for the -following reasons: 在如何代表一个资源没有固定的限定,在Yii中通常使用 [[yii\base\Model]] 或它的子类(如 [[yii\db\ActiveRecord]]) 代表资源,是为以下原因: -* [[yii\base\Model]] implements the [[yii\base\Arrayable]] interface, which allows you to - customize how you want to expose resource data through RESTful APIs. * [[yii\base\Model]] 实现了 [[yii\base\Arrayable]] 接口,它允许你通过RESTful API自定义你想要公开的资源数据。 -* [[yii\base\Model]] supports [input validation](input-validation.md), which is useful if your RESTful APIs - need to support data input. * [[yii\base\Model]] 支持 [输入验证](input-validation.md), 在你的RESTful API需要支持数据输入时非常有用。 -* [[yii\db\ActiveRecord]] provides powerful DB data access and manipulation support, which makes it - a perfect fit if your resource data is stored in databases. * [[yii\db\ActiveRecord]] 提供了强大的数据库访问和操作方面的支持,如资源数据需要存到数据库它提供了完美的支持。 -In this section, we will mainly describe how a resource class extending from [[yii\base\Model]] (or its child classes) -can specify what data may be returned via RESTful APIs. If the resource class does not extend from [[yii\base\Model]], -then all its public member variables will be returned. 本节主要描述资源类如何从 [[yii\base\Model]] (或它的子类) 继承并指定哪些数据可通过RESTful API返回,如果资源类没有 继承 [[yii\base\Model]] 会将它所有的公开成员变量返回。 -## Fields ## 字段 -When including a resource in a RESTful API response, the resource needs to be serialized into a string. -Yii breaks this process into two steps. First, the resource is converted into an array by [[yii\rest\Serializer]]. -Second, the array is serialized into a string in a requested format (e.g. JSON, XML) by -[[yii\web\ResponseFormatterInterface|response formatters]]. The first step is what you should mainly focus when -developing a resource class. 当RESTful API响应中包含一个资源时,该资源需要序列化成一个字符串。 Yii将这个过程分成两步,首先,资源会被[[yii\rest\Serializer]]转换成数组, 然后,该数组会通过[[yii\web\ResponseFormatterInterface|response formatters]]根据请求格式(如JSON, XML)被序列化成字符串。 当开发一个资源类时应重点关注第一步。 -By overriding [[yii\base\Model::fields()|fields()]] and/or [[yii\base\Model::extraFields()|extraFields()]], -you may specify what data, called *fields*, in the resource can be put into its array representation. -The difference between these two methods is that the former specifies the default set of fields which should -be included in the array representation, while the latter specifies additional fields which may be included -in the array if an end user requests for them via the `expand` query parameter. For example, 通过覆盖 [[yii\base\Model::fields()|fields()]] 和/或 [[yii\base\Model::extraFields()|extraFields()]] 方法, 可指定资源中称为 *字段* 的数据放入展现数组中,两个方法的差别为前者指定默认包含到展现数组的字段集合, 后者指定由于终端用户的请求包含 `expand` 参数哪些额外的字段应被包含到展现数组,例如, -``` -// returns all fields as declared in fields() -http://localhost/users - -// only returns field id and email, provided they are declared in fields() -http://localhost/users?fields=id,email - -// returns all fields in fields() and field profile if it is in extraFields() -http://localhost/users?expand=profile - -// only returns field id, email and profile, provided they are in fields() and extraFields() -http://localhost/users?fields=id,email&expand=profile -``` ``` // 返回fields()方法中申明的所有字段 http://localhost/users @@ -81,19 +42,11 @@ http://localhost/users?fields=id,email&expand=profile ``` -### Overriding `fields()` ### 覆盖 `fields()` 方法 -By default, [[yii\base\Model::fields()]] returns all model attributes as fields, while -[[yii\db\ActiveRecord::fields()]] only returns the attributes which have been populated from DB. [[yii\base\Model::fields()]] 默认返回模型的所有属性作为字段, [[yii\db\ActiveRecord::fields()]] 只返回和数据表关联的属性作为字段。 -You can override `fields()` to add, remove, rename or redefine fields. The return value of `fields()` -should be an array. The array keys are the field names, and the array values are the corresponding -field definitions which can be either property/attribute names or anonymous functions returning the -corresponding field values. In the special case when a field name is the same as its defining attribute -name, you can omit the array key. For example, 可覆盖 `fields()` 方法来增加、删除、重命名、重定义字段,`fields()` 的返回值应为数组,数组的键为字段名 数组的值为对应的字段定义,可为属性名或返回对应的字段值的匿名函数,特殊情况下,如果字段名和属性名相同, 可省略数组的键,例如 @@ -126,24 +79,14 @@ public function fields() } ``` -> Warning: Because by default all attributes of a model will be included in the API result, you should -> examine your data to make sure they do not contain sensitive information. If there is such information, -> you should override `fields()` to filter them out. In the above example, we choose -> to filter out `auth_key`, `password_hash` and `password_reset_token`. > 警告: 模型的所有属性默认会被包含到API结果中,应检查数据确保没包含敏感数据,如果有敏感数据, > 应覆盖`fields()`过滤掉,在上述例子中,我们选择过滤掉 `auth_key`, `password_hash` 和 `password_reset_token`. -### Overriding `extraFields()` ### 覆盖 `extraFields()` 方法 -By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]] -returns the names of the relations that have been populated from DB. [[yii\base\Model::extraFields()]] 默认返回空值,[[yii\db\ActiveRecord::extraFields()]] 返回和数据表关联的属性。 -The return data format of `extraFields()` is the same as that of `fields()`. Usually, `extraFields()` -is mainly used to specify fields whose values are objects. For example, given the following field -declaration, `extraFields()` 返回的数据格式和 `fields()` 相同,一般`extraFields()` 主要用于指定哪些值为对象的字段, 例如,给定以下字段申明 @@ -176,7 +119,6 @@ public function extraFields() ``` -## Links ## 链接 [HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), 是Hypermedia as the Engine of Application State的缩写, @@ -216,15 +158,10 @@ class User extends ActiveRecord implements Linkable ``` -## Collections ## 集合 资源对象可以组成 *集合*,每个集合包含一组相同类型的资源对象。 -While collections can be represented as arrays, it is usually more desirable to represent them -as [data providers](output-data-providers.md). This is because data providers support sorting and pagination -of resources, which is a commonly needed feature for RESTful APIs returning collections. For example, -the following action returns a data provider about the post resources: 集合可被展现成数组,更多情况下展现成 [data providers](output-data-providers.md). 因为data providers支持资源的排序和分页,这个特性在 RESTful API 返回集合时也用到,例如This is because data providers support sorting and pagination 如下操作返回post资源的data provider: @@ -250,16 +187,10 @@ class PostController extends Controller 当在RESTful API响应中发送data provider 时, [[yii\rest\Serializer]] 会取出资源的当前页并组装成资源对象数组, [[yii\rest\Serializer]] 也通过如下HTTP头包含页码信息: -* `X-Pagination-Total-Count`: The total number of resources; -* `X-Pagination-Page-Count`: The number of pages; -* `X-Pagination-Current-Page`: The current page (1-based); -* `X-Pagination-Per-Page`: The number of resources in each page; -* `Link`: A set of navigational links allowing client to traverse the resources page by page. * `X-Pagination-Total-Count`: 资源所有数量; * `X-Pagination-Page-Count`: 页数; * `X-Pagination-Current-Page`: 当前页(从1开始); * `X-Pagination-Per-Page`: 每页资源数量; * `Link`: 允许客户端一页一页遍历资源的导航链接集合. -An example may be found in the [Quick Start](rest-quick-start.md#trying-it-out) section. 可在[快速入门](rest-quick-start.md#trying-it-out) 一节中找到样例. From 7603f06135190315d44a2447ee2d908760918134 Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Fri, 26 Dec 2014 16:50:31 +0800 Subject: [PATCH 05/11] english --- docs/guide-zh-CN/rest-authentication.md | 126 ++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 docs/guide-zh-CN/rest-authentication.md diff --git a/docs/guide-zh-CN/rest-authentication.md b/docs/guide-zh-CN/rest-authentication.md new file mode 100644 index 0000000000..11541180c9 --- /dev/null +++ b/docs/guide-zh-CN/rest-authentication.md @@ -0,0 +1,126 @@ +Authentication +============== + +Unlike Web applications, RESTful APIs are usually stateless, which means sessions or cookies should not +be used. Therefore, each request should come with some sort of authentication credentials because +the user authentication status may not be maintained by sessions or cookies. A common practice is +to send a secret access token with each request to authenticate the user. Since an access token +can be used to uniquely identify and authenticate a user, **API requests should always be sent +via HTTPS to prevent man-in-the-middle (MitM) attacks**. + +There are different ways to send an access token: + +* [HTTP Basic Auth](http://en.wikipedia.org/wiki/Basic_access_authentication): the access token + is sent as the username. This should only be used when an access token can be safely stored + on the API consumer side. For example, the API consumer is a program running on a server. +* Query parameter: the access token is sent as a query parameter in the API URL, e.g., + `https://example.com/users?access-token=xxxxxxxx`. Because most Web servers will keep query + parameters in server logs, this approach should be mainly used to serve `JSONP` requests which + cannot use HTTP headers to send access tokens. +* [OAuth 2](http://oauth.net/2/): the access token is obtained by the consumer from an authorization + server and sent to the API server via [HTTP Bearer Tokens](http://tools.ietf.org/html/rfc6750), + according to the OAuth2 protocol. + +Yii supports all of the above authentication methods. You can also easily create new authentication methods. + +To enable authentication for your APIs, do the following steps: + +1. Configure the `user` application component: + - Set the [[yii\web\User::enableSession|enableSession]] property to be `false`. + - Set the [[yii\web\User::loginUrl|loginUrl]] property to be `null` to show a HTTP 403 error instead of redirecting to the login page. +2. Specify which authentication methods you plan to use by configuring the `authenticator` behavior + in your REST controller classes. +3. Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]]. + +Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]] +is false, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication +will be performed for every request, which is accomplished by Step 2 and 3. + +> Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the `user` application component + in application configurations if you are developing RESTful APIs in terms of an application. If you develop + RESTful APIs as a module, you may put the following line in the module's `init()` method, like the following: +> ```php +public function init() +{ + parent::init(); + \Yii::$app->user->enableSession = false; +} +``` + +For example, to use HTTP Basic Auth, you may configure the `authenticator` behavior as follows, + +```php +use yii\filters\auth\HttpBasicAuth; + +public function behaviors() +{ + $behaviors = parent::behaviors(); + $behaviors['authenticator'] = [ + 'class' => HttpBasicAuth::className(), + ]; + return $behaviors; +} +``` + +If you want to support all three authentication methods explained above, you can use `CompositeAuth` like the following, + +```php +use yii\filters\auth\CompositeAuth; +use yii\filters\auth\HttpBasicAuth; +use yii\filters\auth\HttpBearerAuth; +use yii\filters\auth\QueryParamAuth; + +public function behaviors() +{ + $behaviors = parent::behaviors(); + $behaviors['authenticator'] = [ + 'class' => CompositeAuth::className(), + 'authMethods' => [ + HttpBasicAuth::className(), + HttpBearerAuth::className(), + QueryParamAuth::className(), + ], + ]; + return $behaviors; +} +``` + +Each element in `authMethods` should be an auth method class name or a configuration array. + + +Implementation of `findIdentityByAccessToken()` is application specific. For example, in simple scenarios +when each user can only have one access token, you may store the access token in an `access_token` column +in the user table. The method can then be readily implemented in the `User` class as follows, + +```php +use yii\db\ActiveRecord; +use yii\web\IdentityInterface; + +class User extends ActiveRecord implements IdentityInterface +{ + public static function findIdentityByAccessToken($token, $type = null) + { + return static::findOne(['access_token' => $token]); + } +} +``` + +After authentication is enabled as described above, for every API request, the requested controller +will try to authenticate the user in its `beforeAction()` step. + +If authentication succeeds, the controller will perform other checks (such as rate limiting, authorization) +and then run the action. The authenticated user identity information can be retrieved via `Yii::$app->user->identity`. + +If authentication fails, a response with HTTP status 401 will be sent back together with other appropriate headers +(such as a `WWW-Authenticate` header for HTTP Basic Auth). + + +## Authorization + +After a user is authenticated, you probably want to check if he or she has the permission to perform the requested +action for the requested resource. This process is called *authorization* which is covered in detail in +the [Authorization section](security-authorization.md). + +If your controllers extend from [[yii\rest\ActiveController]], you may override +the [[yii\rest\Controller::checkAccess()|checkAccess()]] method to perform authorization check. The method +will be called by the built-in actions provided by [[yii\rest\ActiveController]]. From e6418d40cf87183ddb17adabceac40687de5d8b3 Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Wed, 31 Dec 2014 09:46:26 +0800 Subject: [PATCH 06/11] for check --- docs/guide-zh-CN/rest-authentication.md | 46 ++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/docs/guide-zh-CN/rest-authentication.md b/docs/guide-zh-CN/rest-authentication.md index 11541180c9..3cbbcbdd4d 100644 --- a/docs/guide-zh-CN/rest-authentication.md +++ b/docs/guide-zh-CN/rest-authentication.md @@ -1,4 +1,5 @@ Authentication +认证 ============== Unlike Web applications, RESTful APIs are usually stateless, which means sessions or cookies should not @@ -7,23 +8,34 @@ the user authentication status may not be maintained by sessions or cookies. A c to send a secret access token with each request to authenticate the user. Since an access token can be used to uniquely identify and authenticate a user, **API requests should always be sent via HTTPS to prevent man-in-the-middle (MitM) attacks**. +和Web应用不同,RESTful APIs 通常是无状态的,也就意味着不应使用sessions 或 cookies, +因此每个请求应附带某种授权凭证,因为用户授权状态可能没通过sessions 或 cookies维护, +常用的做法是每个请求都发送一个秘密的access token来认证用户,由于access token可以唯一识别和认证用户, +**API 请求应通过HTTPS来防止man-in-the-middle (MitM) 中间人攻击**. There are different ways to send an access token: +下面有几种方式来发送access token: * [HTTP Basic Auth](http://en.wikipedia.org/wiki/Basic_access_authentication): the access token is sent as the username. This should only be used when an access token can be safely stored on the API consumer side. For example, the API consumer is a program running on a server. +* [HTTP 基本认证](http://en.wikipedia.org/wiki/Basic_access_authentication): access token + 当作用户名发送,应用在access token可安全存在API使用端的场景,例如,API使用端是运行在一台服务器上的程序。 * Query parameter: the access token is sent as a query parameter in the API URL, e.g., `https://example.com/users?access-token=xxxxxxxx`. Because most Web servers will keep query parameters in server logs, this approach should be mainly used to serve `JSONP` requests which cannot use HTTP headers to send access tokens. -* [OAuth 2](http://oauth.net/2/): the access token is obtained by the consumer from an authorization - server and sent to the API server via [HTTP Bearer Tokens](http://tools.ietf.org/html/rfc6750), - according to the OAuth2 protocol. +* 请求参数: access token 当作API URL请求参数发送,例如 + `https://example.com/users?access-token=xxxxxxxx`,由于大多数服务器都会保存请求参数到日志, + 这种方式应主要用于`JSONP` 请求,因为它不能使用HTTP头来发送access token +* [OAuth 2](http://oauth.net/2/): 使用者从认证服务器上获取基于OAuth2协议的access token,然后通过 + [HTTP Bearer Tokens](http://tools.ietf.org/html/rfc6750) 发送到API 服务器。 Yii supports all of the above authentication methods. You can also easily create new authentication methods. +Yii 支持上述的认证方式,你也可很方便的创建新的认证方式。 To enable authentication for your APIs, do the following steps: +为你的APIs启用认证,做以下步骤: 1. Configure the `user` application component: - Set the [[yii\web\User::enableSession|enableSession]] property to be `false`. @@ -31,15 +43,25 @@ To enable authentication for your APIs, do the following steps: 2. Specify which authentication methods you plan to use by configuring the `authenticator` behavior in your REST controller classes. 3. Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]]. +1. 配置`user` 应用组件: + - 设置 [[yii\web\User::enableSession|enableSession]] 属性为 `false`. + - 设置 [[yii\web\User::loginUrl|loginUrl]] 属性为`null` 显示一个HTTP 403 错误而不是跳转到登录界面. +2. 在你的REST 控制器类中配置`authenticator` 行为来指定使用哪种认证方式 +3. 在你的[[yii\web\User::identityClass|user identity class]] 类中实现 [[yii\web\IdentityInterface::findIdentityByAccessToken()]] 方法. Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]] is false, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication will be performed for every request, which is accomplished by Step 2 and 3. +步骤1不是必要的,但是推荐配置,因为RESTful APIs应为无状态的,当[[yii\web\User::enableSession|enableSession]]为false, +请求中的用户认证状态就不能通过session来保持,每个请求的认证通过步骤2和3来实现。 > Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the `user` application component in application configurations if you are developing RESTful APIs in terms of an application. If you develop RESTful APIs as a module, you may put the following line in the module's `init()` method, like the following: -> ```php +> 提示: 如果你将RESTful APIs作为应用开发,可以设置应用配置中 `user` 组件的[[yii\web\User::enableSession|enableSession]], + 如果将RESTful APIs作为模块开发,可以在模块的 `init()` 方法中增加如下代码,如下所示: + +```php public function init() { parent::init(); @@ -48,6 +70,7 @@ public function init() ``` For example, to use HTTP Basic Auth, you may configure the `authenticator` behavior as follows, +例如,为使用HTTP Basic Auth,可配置`authenticator` 行为,如下所示: ```php use yii\filters\auth\HttpBasicAuth; @@ -63,6 +86,7 @@ public function behaviors() ``` If you want to support all three authentication methods explained above, you can use `CompositeAuth` like the following, +如果你系那个支持以上3个认证方式,可以使用`CompositeAuth`,如下所示: ```php use yii\filters\auth\CompositeAuth; @@ -86,11 +110,16 @@ public function behaviors() ``` Each element in `authMethods` should be an auth method class name or a configuration array. +`authMethods` 中每个单元应为一个认证方法名或配置数组。 Implementation of `findIdentityByAccessToken()` is application specific. For example, in simple scenarios when each user can only have one access token, you may store the access token in an `access_token` column in the user table. The method can then be readily implemented in the `User` class as follows, +`findIdentityByAccessToken()`方法的实现是系统定义的, +例如,一个简单的场景,当每个用户只有一个access token, 可存储access token 到user表的`access_token`列中, +方法可在`User`类中简单实现,如下所示: + ```php use yii\db\ActiveRecord; @@ -107,20 +136,29 @@ class User extends ActiveRecord implements IdentityInterface After authentication is enabled as described above, for every API request, the requested controller will try to authenticate the user in its `beforeAction()` step. +在上述认证启用后,对于每个API请求,请求控制器都会在它的`beforeAction()`步骤中对用户进行鉴权。 If authentication succeeds, the controller will perform other checks (such as rate limiting, authorization) and then run the action. The authenticated user identity information can be retrieved via `Yii::$app->user->identity`. +如果认证成功,控制器再执行其他检查(如频率限制,操作权限),然后再执行操作, +授权用户信息可使用`Yii::$app->user->identity`获取. If authentication fails, a response with HTTP status 401 will be sent back together with other appropriate headers (such as a `WWW-Authenticate` header for HTTP Basic Auth). +如果认证失败,会发送一个HTTP状态码为401的响应,并带有其他相关信息头(如HTTP 基本认证会有`WWW-Authenticate` 头信息). ## Authorization +## 授权 After a user is authenticated, you probably want to check if he or she has the permission to perform the requested action for the requested resource. This process is called *authorization* which is covered in detail in the [Authorization section](security-authorization.md). +在用户认证成功后,你可能想要检查他是否有权限执行对应的操作来获取资源,这个过程称为 *authorization* , +详情请参考 [Authorization section](security-authorization.md). If your controllers extend from [[yii\rest\ActiveController]], you may override the [[yii\rest\Controller::checkAccess()|checkAccess()]] method to perform authorization check. The method will be called by the built-in actions provided by [[yii\rest\ActiveController]]. +如果你的控制器从[[yii\rest\ActiveController]]类继承,可覆盖 [[yii\rest\Controller::checkAccess()|checkAccess()]] 方法 +来执行授权检查,该方法会被[[yii\rest\ActiveController]]内置的操作调用。 From 9ef4e42177bfd40c5b3eee93d4e068d2987d58a2 Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Wed, 31 Dec 2014 09:47:31 +0800 Subject: [PATCH 07/11] little fix --- docs/guide-zh-CN/rest-authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide-zh-CN/rest-authentication.md b/docs/guide-zh-CN/rest-authentication.md index 3cbbcbdd4d..33c3c22682 100644 --- a/docs/guide-zh-CN/rest-authentication.md +++ b/docs/guide-zh-CN/rest-authentication.md @@ -136,7 +136,7 @@ class User extends ActiveRecord implements IdentityInterface After authentication is enabled as described above, for every API request, the requested controller will try to authenticate the user in its `beforeAction()` step. -在上述认证启用后,对于每个API请求,请求控制器都会在它的`beforeAction()`步骤中对用户进行鉴权。 +在上述认证启用后,对于每个API请求,请求控制器都会在它的`beforeAction()`步骤中对用户进行认证。 If authentication succeeds, the controller will perform other checks (such as rate limiting, authorization) and then run the action. The authenticated user identity information can be retrieved via `Yii::$app->user->identity`. From 5d74e260f4990cd86f7c219f21f2367cda8aadba Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Wed, 31 Dec 2014 09:49:13 +0800 Subject: [PATCH 08/11] new chinese --- docs/guide-zh-CN/rest-authentication.md | 48 ------------------------- 1 file changed, 48 deletions(-) diff --git a/docs/guide-zh-CN/rest-authentication.md b/docs/guide-zh-CN/rest-authentication.md index 33c3c22682..d2a9aaa9ce 100644 --- a/docs/guide-zh-CN/rest-authentication.md +++ b/docs/guide-zh-CN/rest-authentication.md @@ -1,63 +1,34 @@ -Authentication 认证 ============== -Unlike Web applications, RESTful APIs are usually stateless, which means sessions or cookies should not -be used. Therefore, each request should come with some sort of authentication credentials because -the user authentication status may not be maintained by sessions or cookies. A common practice is -to send a secret access token with each request to authenticate the user. Since an access token -can be used to uniquely identify and authenticate a user, **API requests should always be sent -via HTTPS to prevent man-in-the-middle (MitM) attacks**. 和Web应用不同,RESTful APIs 通常是无状态的,也就意味着不应使用sessions 或 cookies, 因此每个请求应附带某种授权凭证,因为用户授权状态可能没通过sessions 或 cookies维护, 常用的做法是每个请求都发送一个秘密的access token来认证用户,由于access token可以唯一识别和认证用户, **API 请求应通过HTTPS来防止man-in-the-middle (MitM) 中间人攻击**. -There are different ways to send an access token: 下面有几种方式来发送access token: -* [HTTP Basic Auth](http://en.wikipedia.org/wiki/Basic_access_authentication): the access token - is sent as the username. This should only be used when an access token can be safely stored - on the API consumer side. For example, the API consumer is a program running on a server. * [HTTP 基本认证](http://en.wikipedia.org/wiki/Basic_access_authentication): access token 当作用户名发送,应用在access token可安全存在API使用端的场景,例如,API使用端是运行在一台服务器上的程序。 -* Query parameter: the access token is sent as a query parameter in the API URL, e.g., - `https://example.com/users?access-token=xxxxxxxx`. Because most Web servers will keep query - parameters in server logs, this approach should be mainly used to serve `JSONP` requests which - cannot use HTTP headers to send access tokens. * 请求参数: access token 当作API URL请求参数发送,例如 `https://example.com/users?access-token=xxxxxxxx`,由于大多数服务器都会保存请求参数到日志, 这种方式应主要用于`JSONP` 请求,因为它不能使用HTTP头来发送access token * [OAuth 2](http://oauth.net/2/): 使用者从认证服务器上获取基于OAuth2协议的access token,然后通过 [HTTP Bearer Tokens](http://tools.ietf.org/html/rfc6750) 发送到API 服务器。 -Yii supports all of the above authentication methods. You can also easily create new authentication methods. Yii 支持上述的认证方式,你也可很方便的创建新的认证方式。 -To enable authentication for your APIs, do the following steps: 为你的APIs启用认证,做以下步骤: -1. Configure the `user` application component: - - Set the [[yii\web\User::enableSession|enableSession]] property to be `false`. - - Set the [[yii\web\User::loginUrl|loginUrl]] property to be `null` to show a HTTP 403 error instead of redirecting to the login page. -2. Specify which authentication methods you plan to use by configuring the `authenticator` behavior - in your REST controller classes. -3. Implement [[yii\web\IdentityInterface::findIdentityByAccessToken()]] in your [[yii\web\User::identityClass|user identity class]]. 1. 配置`user` 应用组件: - 设置 [[yii\web\User::enableSession|enableSession]] 属性为 `false`. - 设置 [[yii\web\User::loginUrl|loginUrl]] 属性为`null` 显示一个HTTP 403 错误而不是跳转到登录界面. 2. 在你的REST 控制器类中配置`authenticator` 行为来指定使用哪种认证方式 3. 在你的[[yii\web\User::identityClass|user identity class]] 类中实现 [[yii\web\IdentityInterface::findIdentityByAccessToken()]] 方法. -Step 1 is not required but is recommended for RESTful APIs which should be stateless. When [[yii\web\User::enableSession|enableSession]] -is false, the user authentication status will NOT be persisted across requests using sessions. Instead, authentication -will be performed for every request, which is accomplished by Step 2 and 3. 步骤1不是必要的,但是推荐配置,因为RESTful APIs应为无状态的,当[[yii\web\User::enableSession|enableSession]]为false, 请求中的用户认证状态就不能通过session来保持,每个请求的认证通过步骤2和3来实现。 -> Tip: You may configure [[yii\web\User::enableSession|enableSession]] of the `user` application component - in application configurations if you are developing RESTful APIs in terms of an application. If you develop - RESTful APIs as a module, you may put the following line in the module's `init()` method, like the following: > 提示: 如果你将RESTful APIs作为应用开发,可以设置应用配置中 `user` 组件的[[yii\web\User::enableSession|enableSession]], 如果将RESTful APIs作为模块开发,可以在模块的 `init()` 方法中增加如下代码,如下所示: @@ -69,7 +40,6 @@ public function init() } ``` -For example, to use HTTP Basic Auth, you may configure the `authenticator` behavior as follows, 例如,为使用HTTP Basic Auth,可配置`authenticator` 行为,如下所示: ```php @@ -85,7 +55,6 @@ public function behaviors() } ``` -If you want to support all three authentication methods explained above, you can use `CompositeAuth` like the following, 如果你系那个支持以上3个认证方式,可以使用`CompositeAuth`,如下所示: ```php @@ -109,13 +78,9 @@ public function behaviors() } ``` -Each element in `authMethods` should be an auth method class name or a configuration array. `authMethods` 中每个单元应为一个认证方法名或配置数组。 -Implementation of `findIdentityByAccessToken()` is application specific. For example, in simple scenarios -when each user can only have one access token, you may store the access token in an `access_token` column -in the user table. The method can then be readily implemented in the `User` class as follows, `findIdentityByAccessToken()`方法的实现是系统定义的, 例如,一个简单的场景,当每个用户只有一个access token, 可存储access token 到user表的`access_token`列中, 方法可在`User`类中简单实现,如下所示: @@ -134,31 +99,18 @@ class User extends ActiveRecord implements IdentityInterface } ``` -After authentication is enabled as described above, for every API request, the requested controller -will try to authenticate the user in its `beforeAction()` step. 在上述认证启用后,对于每个API请求,请求控制器都会在它的`beforeAction()`步骤中对用户进行认证。 -If authentication succeeds, the controller will perform other checks (such as rate limiting, authorization) -and then run the action. The authenticated user identity information can be retrieved via `Yii::$app->user->identity`. 如果认证成功,控制器再执行其他检查(如频率限制,操作权限),然后再执行操作, 授权用户信息可使用`Yii::$app->user->identity`获取. -If authentication fails, a response with HTTP status 401 will be sent back together with other appropriate headers -(such as a `WWW-Authenticate` header for HTTP Basic Auth). 如果认证失败,会发送一个HTTP状态码为401的响应,并带有其他相关信息头(如HTTP 基本认证会有`WWW-Authenticate` 头信息). -## Authorization ## 授权 -After a user is authenticated, you probably want to check if he or she has the permission to perform the requested -action for the requested resource. This process is called *authorization* which is covered in detail in -the [Authorization section](security-authorization.md). 在用户认证成功后,你可能想要检查他是否有权限执行对应的操作来获取资源,这个过程称为 *authorization* , 详情请参考 [Authorization section](security-authorization.md). -If your controllers extend from [[yii\rest\ActiveController]], you may override -the [[yii\rest\Controller::checkAccess()|checkAccess()]] method to perform authorization check. The method -will be called by the built-in actions provided by [[yii\rest\ActiveController]]. 如果你的控制器从[[yii\rest\ActiveController]]类继承,可覆盖 [[yii\rest\Controller::checkAccess()|checkAccess()]] 方法 来执行授权检查,该方法会被[[yii\rest\ActiveController]]内置的操作调用。 From 031ef95b466c4d3fe51ca98426bdf004c706e4f0 Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Sun, 4 Jan 2015 10:39:07 +0800 Subject: [PATCH 09/11] for check --- docs/guide-zh-CN/rest-controllers.md | 204 +++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 docs/guide-zh-CN/rest-controllers.md diff --git a/docs/guide-zh-CN/rest-controllers.md b/docs/guide-zh-CN/rest-controllers.md new file mode 100644 index 0000000000..e06caa4013 --- /dev/null +++ b/docs/guide-zh-CN/rest-controllers.md @@ -0,0 +1,204 @@ +Controllers +控制器 +=========== + +After creating the resource classes and specifying how resource data should be formatted, the next thing +to do is to create controller actions to expose the resources to end users through RESTful APIs. +在创建资源类和指定资源格输出式化后,下一步就是创建控制器操作将资源通过RESTful APIs展现给终端用户。 + +Yii provides two base controller classes to simplify your work of creating RESTful actions: +[[yii\rest\Controller]] and [[yii\rest\ActiveController]]. The difference between these two controllers +is that the latter provides a default set of actions that are specifically designed to deal with +resources represented as [Active Record](db-active-record.md). So if you are using [Active Record](db-active-record.md) +and are comfortable with the provided built-in actions, you may consider extending your controller classes +from [[yii\rest\ActiveController]], which will allow you to create powerful RESTful APIs with minimal code. +Yii 提供两个控制器基类来简化创建RESTful 操作的工作:[[yii\rest\Controller]] 和 [[yii\rest\ActiveController]], +两个类的差别是后者提供一系列将资源处理成[Active Record](db-active-record.md)的操作。 +因此如果使用[Active Record](db-active-record.md)内置的操作会比较方便,可考虑将控制器类 +继承[[yii\rest\ActiveController]],它会让你用最少的代码完成强大的RESTful APIs. + +Both [[yii\rest\Controller]] and [[yii\rest\ActiveController]] provide the following features, some of which +will be described in detail in the next few sections: +[[yii\rest\Controller]] 和 [[yii\rest\ActiveController]] 提供以下功能,一些功能在后续章节详细描述: + +* HTTP method validation; +* [Content negotiation and Data formatting](rest-response-formatting.md); +* [Authentication](rest-authentication.md); +* [Rate limiting](rest-rate-limiting.md). +* HTTP 方法验证; +* [内容协商和数据格式化](rest-response-formatting.md); +* [认证](rest-authentication.md); +* [频率限制](rest-rate-limiting.md). + +[[yii\rest\ActiveController]] in addition provides the following features: +[[yii\rest\ActiveController]] 额外提供一下功能: + +* A set of commonly needed actions: `index`, `view`, `create`, `update`, `delete`, `options`; +* User authorization in regarding to the requested action and resource. +* 一系列常用操作: `index`, `view`, `create`, `update`, `delete`, `options`; +* 对操作和资源进行用户认证. + + +## Creating Controller Classes +## 创建控制器类 + +When creating a new controller class, a convention in naming the controller class is to use +the type name of the resource and use singular form. For example, to serve user information, +the controller may be named as `UserController`. +当创建一个新的控制器类,控制器类的命名最好使用资源名称的单数格式,例如,提供用户信息的控制器 +可命名为`UserController`. + +Creating a new action is similar to creating an action for a Web application. The only difference +is that instead of rendering the result using a view by calling the `render()` method, for RESTful actions +you directly return the data. The [[yii\rest\Controller::serializer|serializer]] and the +[[yii\web\Response|response object]] will handle the conversion from the original data to the requested +format. For example, +创建新的操作和Web应用中创建操作类似,唯一的差别是Web应用中调用`render()`方法渲染一个视图作为返回值, +对于RESTful操作直接返回数据,[[yii\rest\Controller::serializer|serializer]] 和 +[[yii\web\Response|response object]] 会处理原始数据到请求格式的转换,例如 + +```php +public function actionView($id) +{ + return User::findOne($id); +} +``` + + +## Filters +## 过滤器 + +Most RESTful API features provided by [[yii\rest\Controller]] are implemented in terms of [filters](structure-filters.md). +In particular, the following filters will be executed in the order they are listed: +[[yii\rest\Controller]]提供的大多数RESTful API功能通过[过滤器](structure-filters.md)实现. +特别是以下过滤器会按顺序执行: + +* [[yii\filters\ContentNegotiator|contentNegotiator]]: supports content negotiation, to be explained in + the [Response Formatting](rest-response-formatting.md) section; +* [[yii\filters\ContentNegotiator|contentNegotiator]]: 支持内容协商,在 [响应格式化](rest-response-formatting.md) 一节描述; +* [[yii\filters\VerbFilter|verbFilter]]: supports HTTP method validation; +* [[yii\filters\VerbFilter|verbFilter]]: 支持HTTP 方法验证; +* [[yii\filters\AuthMethod|authenticator]]: supports user authentication, to be explained in + the [Authentication](rest-authentication.md) section; +* [[yii\filters\AuthMethod|authenticator]]: 支持用户认证,在[认证](rest-authentication.md)一节描述; +* [[yii\filters\RateLimiter|rateLimiter]]: 支持频率限制,在[频率限制](rest-rate-limiting.md) 一节描述. +* [[yii\filters\RateLimiter|rateLimiter]]: supports rate limiting, to be explained in + the [Rate Limiting](rest-rate-limiting.md) section. + +These named filters are declared in the [[yii\rest\Controller::behaviors()|behaviors()]] method. +You may override this method to configure individual filters, disable some of them, or add your own filters. +For example, if you only want to use HTTP basic authentication, you may write the following code: +这些过滤器都在[[yii\rest\Controller::behaviors()|behaviors()]]方法中声明, +可覆盖该方法来配置单独的过滤器,禁用某个或增加你自定义的过滤器。 +例如,如果你只想用HTTP 基础认证,可编写如下代码: + +```php +use yii\filters\auth\HttpBasicAuth; + +public function behaviors() +{ + $behaviors = parent::behaviors(); + $behaviors['authenticator'] = [ + 'class' => HttpBasicAuth::className(), + ]; + return $behaviors; +} +``` + + +## Extending `ActiveController` +## 继承 `ActiveController` + +If your controller class extends from [[yii\rest\ActiveController]], you should set +its [[yii\rest\ActiveController::modelClass||modelClass]] property to be the name of the resource class +that you plan to serve through this controller. The class must extend from [[yii\db\ActiveRecord]]. +如果你的控制器继承[[yii\rest\ActiveController]],应设置[[yii\rest\ActiveController::modelClass||modelClass]] 属性 +为通过该控制器返回给用户的资源类名,该类必须继承[[yii\db\ActiveRecord]]. + + +### Customizing Actions +### 自定义操作 + +By default, [[yii\rest\ActiveController]] provides the following actions: +[[yii\rest\ActiveController]] 默认提供一下操作: + +* [[yii\rest\IndexAction|index]]: list resources page by page; +* [[yii\rest\ViewAction|view]]: return the details of a specified resource; +* [[yii\rest\CreateAction|create]]: create a new resource; +* [[yii\rest\UpdateAction|update]]: update an existing resource; +* [[yii\rest\DeleteAction|delete]]: delete the specified resource; +* [[yii\rest\OptionsAction|options]]: return the supported HTTP methods. +* [[yii\rest\IndexAction|index]]: 按页列出资源; +* [[yii\rest\ViewAction|view]]: 返回指定资源的详情; +* [[yii\rest\CreateAction|create]]: 创建新的资源; +* [[yii\rest\UpdateAction|update]]: 更新一个存在的资源; +* [[yii\rest\DeleteAction|delete]]: 删除指定的资源; +* [[yii\rest\OptionsAction|options]]: 返回支持的HTTP方法. + +All these actions are declared through the [[yii\rest\ActiveController::actions()|actions()]] method. +You may configure these actions or disable some of them by overriding the `actions()` method, like shown the following, +所有这些操作通过[[yii\rest\ActiveController::actions()|actions()]] 方法申明,可覆盖`actions()`方法配置或禁用这些操作, +如下所示: + +```php +public function actions() +{ + $actions = parent::actions(); + + // 禁用"delete" 和 "create" 操作 + unset($actions['delete'], $actions['create']); + + // 使用"prepareDataProvider()"方法自定义数据provider + $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider']; + + return $actions; +} + +public function prepareDataProvider() +{ + // 为"index"操作准备和返回数据provider +} +``` + +Please refer to the class references for individual action classes to learn what configuration options are available. +请参考独立操作类的参考文档学习哪些配置项有用。 + + +### Performing Access Check +### 执行访问检查 + +When exposing resources through RESTful APIs, you often need to check if the current user has the permission +to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done +by overriding the [[yii\rest\ActiveController::checkAccess()|checkAccess()]] method like the following, +通过RESTful APIs显示数据时,经常需要检查当前用户是否有权限访问和操作所请求的资源, +在[[yii\rest\ActiveController]]中,可覆盖[[yii\rest\ActiveController::checkAccess()|checkAccess()]]方法来完成权限检查。 + +```php +/** + * Checks the privilege of the current user. 检查当前用户的权限 + * + * This method should be overridden to check whether the current user has the privilege + * to run the specified action against the specified data model. + * If the user does not have access, a [[ForbiddenHttpException]] should be thrown. + * 本方法应被覆盖来检查当前用户是否有权限执行指定的操作访问指定的数据模型 + * 如果用户没有权限,应抛出一个[[ForbiddenHttpException]]异常 + * + * @param string $action the ID of the action to be executed + * @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed. + * @param array $params additional parameters + * @throws ForbiddenHttpException if the user does not have access + */ +public function checkAccess($action, $model = null, $params = []) +{ + // 检查用户能否访问 $action 和 $model + // 访问被拒绝应抛出ForbiddenHttpException +} +``` + +The `checkAccess()` method will be called by the default actions of [[yii\rest\ActiveController]]. If you create +new actions and also want to perform access check, you should call this method explicitly in the new actions. +`checkAccess()` 方法默认会被[[yii\rest\ActiveController]]默认操作所调用,如果创建新的操作并想执行权限检查, +应在新的操作中明确调用该方法。 + +> Tip: You may implement `checkAccess()` by using the [Role-Based Access Control (RBAC) component](security-authorization.md). +> 提示: 可使用[Role-Based Access Control (RBAC) 基于角色权限控制组件](security-authorization.md)实现`checkAccess()`。 From b613f26b7f245b59346d457d188c0c2f3d8cc386 Mon Sep 17 00:00:00 2001 From: Funson Lee Date: Sun, 4 Jan 2015 10:41:34 +0800 Subject: [PATCH 10/11] new chinese translation --- docs/guide-zh-CN/rest-controllers.md | 61 ---------------------------- 1 file changed, 61 deletions(-) diff --git a/docs/guide-zh-CN/rest-controllers.md b/docs/guide-zh-CN/rest-controllers.md index e06caa4013..cb50f047e8 100644 --- a/docs/guide-zh-CN/rest-controllers.md +++ b/docs/guide-zh-CN/rest-controllers.md @@ -1,58 +1,31 @@ -Controllers 控制器 =========== -After creating the resource classes and specifying how resource data should be formatted, the next thing -to do is to create controller actions to expose the resources to end users through RESTful APIs. 在创建资源类和指定资源格输出式化后,下一步就是创建控制器操作将资源通过RESTful APIs展现给终端用户。 -Yii provides two base controller classes to simplify your work of creating RESTful actions: -[[yii\rest\Controller]] and [[yii\rest\ActiveController]]. The difference between these two controllers -is that the latter provides a default set of actions that are specifically designed to deal with -resources represented as [Active Record](db-active-record.md). So if you are using [Active Record](db-active-record.md) -and are comfortable with the provided built-in actions, you may consider extending your controller classes -from [[yii\rest\ActiveController]], which will allow you to create powerful RESTful APIs with minimal code. Yii 提供两个控制器基类来简化创建RESTful 操作的工作:[[yii\rest\Controller]] 和 [[yii\rest\ActiveController]], 两个类的差别是后者提供一系列将资源处理成[Active Record](db-active-record.md)的操作。 因此如果使用[Active Record](db-active-record.md)内置的操作会比较方便,可考虑将控制器类 继承[[yii\rest\ActiveController]],它会让你用最少的代码完成强大的RESTful APIs. -Both [[yii\rest\Controller]] and [[yii\rest\ActiveController]] provide the following features, some of which -will be described in detail in the next few sections: [[yii\rest\Controller]] 和 [[yii\rest\ActiveController]] 提供以下功能,一些功能在后续章节详细描述: -* HTTP method validation; -* [Content negotiation and Data formatting](rest-response-formatting.md); -* [Authentication](rest-authentication.md); -* [Rate limiting](rest-rate-limiting.md). * HTTP 方法验证; * [内容协商和数据格式化](rest-response-formatting.md); * [认证](rest-authentication.md); * [频率限制](rest-rate-limiting.md). -[[yii\rest\ActiveController]] in addition provides the following features: [[yii\rest\ActiveController]] 额外提供一下功能: -* A set of commonly needed actions: `index`, `view`, `create`, `update`, `delete`, `options`; -* User authorization in regarding to the requested action and resource. * 一系列常用操作: `index`, `view`, `create`, `update`, `delete`, `options`; * 对操作和资源进行用户认证. -## Creating Controller Classes ## 创建控制器类 -When creating a new controller class, a convention in naming the controller class is to use -the type name of the resource and use singular form. For example, to serve user information, -the controller may be named as `UserController`. 当创建一个新的控制器类,控制器类的命名最好使用资源名称的单数格式,例如,提供用户信息的控制器 可命名为`UserController`. -Creating a new action is similar to creating an action for a Web application. The only difference -is that instead of rendering the result using a view by calling the `render()` method, for RESTful actions -you directly return the data. The [[yii\rest\Controller::serializer|serializer]] and the -[[yii\web\Response|response object]] will handle the conversion from the original data to the requested -format. For example, 创建新的操作和Web应用中创建操作类似,唯一的差别是Web应用中调用`render()`方法渲染一个视图作为返回值, 对于RESTful操作直接返回数据,[[yii\rest\Controller::serializer|serializer]] 和 [[yii\web\Response|response object]] 会处理原始数据到请求格式的转换,例如 @@ -65,29 +38,17 @@ public function actionView($id) ``` -## Filters ## 过滤器 -Most RESTful API features provided by [[yii\rest\Controller]] are implemented in terms of [filters](structure-filters.md). -In particular, the following filters will be executed in the order they are listed: [[yii\rest\Controller]]提供的大多数RESTful API功能通过[过滤器](structure-filters.md)实现. 特别是以下过滤器会按顺序执行: -* [[yii\filters\ContentNegotiator|contentNegotiator]]: supports content negotiation, to be explained in - the [Response Formatting](rest-response-formatting.md) section; * [[yii\filters\ContentNegotiator|contentNegotiator]]: 支持内容协商,在 [响应格式化](rest-response-formatting.md) 一节描述; -* [[yii\filters\VerbFilter|verbFilter]]: supports HTTP method validation; * [[yii\filters\VerbFilter|verbFilter]]: 支持HTTP 方法验证; -* [[yii\filters\AuthMethod|authenticator]]: supports user authentication, to be explained in the [Authentication](rest-authentication.md) section; * [[yii\filters\AuthMethod|authenticator]]: 支持用户认证,在[认证](rest-authentication.md)一节描述; * [[yii\filters\RateLimiter|rateLimiter]]: 支持频率限制,在[频率限制](rest-rate-limiting.md) 一节描述. -* [[yii\filters\RateLimiter|rateLimiter]]: supports rate limiting, to be explained in - the [Rate Limiting](rest-rate-limiting.md) section. -These named filters are declared in the [[yii\rest\Controller::behaviors()|behaviors()]] method. -You may override this method to configure individual filters, disable some of them, or add your own filters. -For example, if you only want to use HTTP basic authentication, you may write the following code: 这些过滤器都在[[yii\rest\Controller::behaviors()|behaviors()]]方法中声明, 可覆盖该方法来配置单独的过滤器,禁用某个或增加你自定义的过滤器。 例如,如果你只想用HTTP 基础认证,可编写如下代码: @@ -106,28 +67,16 @@ public function behaviors() ``` -## Extending `ActiveController` ## 继承 `ActiveController` -If your controller class extends from [[yii\rest\ActiveController]], you should set -its [[yii\rest\ActiveController::modelClass||modelClass]] property to be the name of the resource class -that you plan to serve through this controller. The class must extend from [[yii\db\ActiveRecord]]. 如果你的控制器继承[[yii\rest\ActiveController]],应设置[[yii\rest\ActiveController::modelClass||modelClass]] 属性 为通过该控制器返回给用户的资源类名,该类必须继承[[yii\db\ActiveRecord]]. -### Customizing Actions ### 自定义操作 -By default, [[yii\rest\ActiveController]] provides the following actions: [[yii\rest\ActiveController]] 默认提供一下操作: -* [[yii\rest\IndexAction|index]]: list resources page by page; -* [[yii\rest\ViewAction|view]]: return the details of a specified resource; -* [[yii\rest\CreateAction|create]]: create a new resource; -* [[yii\rest\UpdateAction|update]]: update an existing resource; -* [[yii\rest\DeleteAction|delete]]: delete the specified resource; -* [[yii\rest\OptionsAction|options]]: return the supported HTTP methods. * [[yii\rest\IndexAction|index]]: 按页列出资源; * [[yii\rest\ViewAction|view]]: 返回指定资源的详情; * [[yii\rest\CreateAction|create]]: 创建新的资源; @@ -135,8 +84,6 @@ By default, [[yii\rest\ActiveController]] provides the following actions: * [[yii\rest\DeleteAction|delete]]: 删除指定的资源; * [[yii\rest\OptionsAction|options]]: 返回支持的HTTP方法. -All these actions are declared through the [[yii\rest\ActiveController::actions()|actions()]] method. -You may configure these actions or disable some of them by overriding the `actions()` method, like shown the following, 所有这些操作通过[[yii\rest\ActiveController::actions()|actions()]] 方法申明,可覆盖`actions()`方法配置或禁用这些操作, 如下所示: @@ -160,16 +107,11 @@ public function prepareDataProvider() } ``` -Please refer to the class references for individual action classes to learn what configuration options are available. 请参考独立操作类的参考文档学习哪些配置项有用。 -### Performing Access Check ### 执行访问检查 -When exposing resources through RESTful APIs, you often need to check if the current user has the permission -to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done -by overriding the [[yii\rest\ActiveController::checkAccess()|checkAccess()]] method like the following, 通过RESTful APIs显示数据时,经常需要检查当前用户是否有权限访问和操作所请求的资源, 在[[yii\rest\ActiveController]]中,可覆盖[[yii\rest\ActiveController::checkAccess()|checkAccess()]]方法来完成权限检查。 @@ -195,10 +137,7 @@ public function checkAccess($action, $model = null, $params = []) } ``` -The `checkAccess()` method will be called by the default actions of [[yii\rest\ActiveController]]. If you create -new actions and also want to perform access check, you should call this method explicitly in the new actions. `checkAccess()` 方法默认会被[[yii\rest\ActiveController]]默认操作所调用,如果创建新的操作并想执行权限检查, 应在新的操作中明确调用该方法。 -> Tip: You may implement `checkAccess()` by using the [Role-Based Access Control (RBAC) component](security-authorization.md). > 提示: 可使用[Role-Based Access Control (RBAC) 基于角色权限控制组件](security-authorization.md)实现`checkAccess()`。 From 8cf6acdca286336bbf06105fb2a42e022c4a33e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E7=94=9F?= Date: Sun, 4 Jan 2015 11:20:56 +0800 Subject: [PATCH 11/11] Rest controller --- docs/guide-zh-CN/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guide-zh-CN/README.md b/docs/guide-zh-CN/README.md index 0a9d686e11..c439cc03da 100644 --- a/docs/guide-zh-CN/README.md +++ b/docs/guide-zh-CN/README.md @@ -119,6 +119,7 @@ RESTful Web 服务 * **已定稿** [快速入门](rest-quick-start.md) * **已定稿** [资源](rest-resources.md) +* **已定稿** [控制器](rest-controllers.md) * **已定稿** [路由](rest-routing.md) * **已定稿** [格式化响应](rest-response-formatting.md) * **已定稿** [授权验证](rest-authentication.md)