From c9f8644d2b5745027b94c1db2b9b58873f037be6 Mon Sep 17 00:00:00 2001 From: Dmitry Korolev Date: Sat, 30 Aug 2014 15:49:25 +0400 Subject: [PATCH 1/4] start working on translation --- docs/guide-ru/rest-response-formatting.md | 150 ++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 docs/guide-ru/rest-response-formatting.md diff --git a/docs/guide-ru/rest-response-formatting.md b/docs/guide-ru/rest-response-formatting.md new file mode 100644 index 0000000000..68badfc5d4 --- /dev/null +++ b/docs/guide-ru/rest-response-formatting.md @@ -0,0 +1,150 @@ +Response Formatting +=================== + +When handling a RESTful API request, an application usually takes the following steps that are related +with response formatting: + +1. Determine various factors that may affect the response format, such as media type, language, version, etc. + This process is also known as [content negotiation](http://en.wikipedia.org/wiki/Content_negotiation). +2. Convert resource objects into arrays, as described in the [Resources](rest-resources.md) section. + This is done by [[yii\rest\Serializer]]. +3. Convert arrays into a string in the format as determined by the content negotiation step. This is + done by [[yii\web\ResponseFormatterInterface|response formatters]] registered with + the [[yii\web\Response::formatters|response]] application component. + + +## Content Negotiation + +Yii supports content negotiation via the [[yii\filters\ContentNegotiator]] filter. The RESTful API base +controller class [[yii\rest\Controller]] is equipped with this filter under the name of `contentNegotiator`. +The filer provides response format negotiation as well as language negotiation. For example, if a RESTful +API request contains the following header, + +``` +Accept: application/json; q=1.0, */*; q=0.1 +``` + +it will get a response in JSON format, like the following: + +``` +$ 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: ; rel=self, + ; rel=next, + ; rel=last +Transfer-Encoding: chunked +Content-Type: application/json; charset=UTF-8 + +[ + { + "id": 1, + ... + }, + { + "id": 2, + ... + }, + ... +] +``` + +Behind the scene, before a RESTful API controller action is executed, the [[yii\filters\ContentNegotiator]] +filter will check the `Accept` HTTP header in the request and set the [[yii\web\Response::format|response format]] +to be `'json'`. After the action is executed and returns the resulting resource object or collection, +[[yii\rest\Serializer]] will convert the result into an array. And finally, [[yii\web\JsonResponseFormatter]] +will serialize the array into a JSON string and include it in the response body. + +By default, RESTful APIs support both JSON and XML formats. To support a new format, you should configure +the [[yii\filters\ContentNegotiator::formats|formats]] property of the `contentNegotiator` filter like +the following in your API controller classes: + +```php +use yii\web\Response; + +public function behaviors() +{ + $behaviors = parent::behaviors(); + $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_HTML; + return $behaviors; +} +``` + +The keys of the `formats` property are the supported MIME types, while the values are the corresponding +response format names which must be supported in [[yii\web\Response::formatters]]. + + +## Data Serializing + +As we have described above, [[yii\rest\Serializer]] is the central piece responsible for converting resource +objects or collections into arrays. It recognizes objects implementing [[yii\base\ArrayableInterface]] as +well as [[yii\data\DataProviderInterface]]. The former is mainly implemented by resource objects, while +the latter resource collections. + +You may configure the serializer by setting the [[yii\rest\Controller::serializer]] property with a configuration array. +For example, sometimes you may want to help simplify the client development work by including pagination information +directly in the response body. To do so, configure the [[yii\rest\Serializer::collectionEnvelope]] property +as follows: + +```php +use yii\rest\ActiveController; + +class UserController extends ActiveController +{ + public $modelClass = 'app\models\User'; + public $serializer = [ + 'class' => 'yii\rest\Serializer', + 'collectionEnvelope' => 'items', + ]; +} +``` + +You may then get the following response for request `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: ; rel=self, + ; rel=next, + ; rel=last +Transfer-Encoding: chunked +Content-Type: application/json; charset=UTF-8 + +{ + "items": [ + { + "id": 1, + ... + }, + { + "id": 2, + ... + }, + ... + ], + "_links": { + "self": "http://localhost/users?page=1", + "next": "http://localhost/users?page=2", + "last": "http://localhost/users?page=50" + }, + "_meta": { + "totalCount": 1000, + "pageCount": 50, + "currentPage": 1, + "perPage": 20 + } +} +``` From abbdf10c0393a17a084849640a284e0d07e2af61 Mon Sep 17 00:00:00 2001 From: Dmitry Korolev Date: Sun, 31 Aug 2014 15:08:07 +0400 Subject: [PATCH 2/4] content translated --- docs/guide-ru/rest-response-formatting.md | 71 +++++++++++------------ 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/docs/guide-ru/rest-response-formatting.md b/docs/guide-ru/rest-response-formatting.md index 68badfc5d4..5f118d8960 100644 --- a/docs/guide-ru/rest-response-formatting.md +++ b/docs/guide-ru/rest-response-formatting.md @@ -1,30 +1,29 @@ -Response Formatting +Форматирование ответа =================== -When handling a RESTful API request, an application usually takes the following steps that are related -with response formatting: +При обработке RESTful API запросов приложение обычно выполняет следующие шаги, связанные с форматированием ответа: -1. Determine various factors that may affect the response format, such as media type, language, version, etc. - This process is also known as [content negotiation](http://en.wikipedia.org/wiki/Content_negotiation). -2. Convert resource objects into arrays, as described in the [Resources](rest-resources.md) section. - This is done by [[yii\rest\Serializer]]. -3. Convert arrays into a string in the format as determined by the content negotiation step. This is - done by [[yii\web\ResponseFormatterInterface|response formatters]] registered with - the [[yii\web\Response::formatters|response]] application component. +1. Определяет различные факторы, которые могут повлиять на формат ответа, такие как media type, язык, версия и т.д. + Этот процесс также известен как [обсуждение содержимого](http://en.wikipedia.org/wiki/Content_negotiation). +2. Конвертирует объекты ресурсов в массивы, как описано в секции [Ресурсы](rest-resources.md). + Это задача для [[yii\rest\Serializer]]. +3. Конвертирует массивы в строке в формате, определенном на этапе обсуждения содержимого. Это задача для + [[yii\web\ResponseFormatterInterface|форматера ответов]], регистрируемого с помощью компонента приложения + [[yii\web\Response::formatters|response]]. -## Content Negotiation +## Обсуждение содержимого -Yii supports content negotiation via the [[yii\filters\ContentNegotiator]] filter. The RESTful API base -controller class [[yii\rest\Controller]] is equipped with this filter under the name of `contentNegotiator`. -The filer provides response format negotiation as well as language negotiation. For example, if a RESTful -API request contains the following header, +Yii поддерживает обсуждение содержимого с помощью фильтра [yii\filters\ContentNegotiator]]. Базовый класс +контроллера RESTful API [[yii\rest\Controller]] использует этот фильтр под именем `contentNegotiator`. +Фильтр обеспечивает соответствие формата ответа и определение языка. Например, если RESTful API запрос +содержит следующий заголовок: ``` Accept: application/json; q=1.0, */*; q=0.1 ``` -it will get a response in JSON format, like the following: +Он будет получать ответ в формате JSON следующего вида: ``` $ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users" @@ -56,15 +55,15 @@ Content-Type: application/json; charset=UTF-8 ] ``` -Behind the scene, before a RESTful API controller action is executed, the [[yii\filters\ContentNegotiator]] -filter will check the `Accept` HTTP header in the request and set the [[yii\web\Response::format|response format]] -to be `'json'`. After the action is executed and returns the resulting resource object or collection, -[[yii\rest\Serializer]] will convert the result into an array. And finally, [[yii\web\JsonResponseFormatter]] -will serialize the array into a JSON string and include it in the response body. +Под копотом происходит следующее: прежде, чем экшн RESTful API контроллера будет выполнен, фильтр +[[yii\filters\ContentNegotiator]] проверит HTTP-заголовок `Accept` в запросе и установит, что +[[yii\web\Response::format|формат ответа]] должен быть в `'json'`. После того, как экшн будет выполнен и вернет +результирующий объект ресурса или коллекцию, [[yii\rest\Serializer]] конвертирует результат в массив. +И, наконец, [[yii\web\JsonResponseFormatter]] сериализует массив в строку JSON и включит ее в тело ответа. -By default, RESTful APIs support both JSON and XML formats. To support a new format, you should configure -the [[yii\filters\ContentNegotiator::formats|formats]] property of the `contentNegotiator` filter like -the following in your API controller classes: +По умолчанию, RESTful APIs поддерживает и JSON, и XML форматы. Для того, чтобы добавить поддержку нового формата, +вы должны установить свою конфигурацию для свойства [[yii\filters\ContentNegotiator::formats|formats]] у фильтра +`contentNegotiator`, похожую на следующие классы контроллеров API: ```php use yii\web\Response; @@ -77,21 +76,21 @@ public function behaviors() } ``` -The keys of the `formats` property are the supported MIME types, while the values are the corresponding -response format names which must be supported in [[yii\web\Response::formatters]]. +Ключи свойства `formats` - это поддерживаемые MIME-типы, а их значения должны соответствовать именам +форматов ответа, которые установлены в [[yii\web\Response::formatters]]. -## Data Serializing +## Сериализация данных -As we have described above, [[yii\rest\Serializer]] is the central piece responsible for converting resource -objects or collections into arrays. It recognizes objects implementing [[yii\base\ArrayableInterface]] as -well as [[yii\data\DataProviderInterface]]. The former is mainly implemented by resource objects, while -the latter resource collections. +Как уже описано выше, [[yii\rest\Serializer]] - это центральное место, отвечащее за конвертацию объектов ресурсов +или коллекций в массивы. Он реализует интерфейсы [[yii\base\ArrayableInterface]] и [[yii\data\DataProviderInterface]]. +[[yii\base\ArrayableInterface]] реализуется для объектов ресурсов, а [[yii\data\DataProviderInterface]] - для коллекций. + +Вы можете переконфигурировать сереализатор с помощью настройки свойства [[yii\rest\Controller::serializer]], используя +конфигурационный массив. Например, иногда вам может быть нужно помочь упростить разработку на клиенте с помощью +добавления информации о пагинации непосредственно в тело ответа. Чтобы сделать это, переконфигурируйте свойство +[[yii\rest\Serializer::collectionEnvelope]] следующим образом: -You may configure the serializer by setting the [[yii\rest\Controller::serializer]] property with a configuration array. -For example, sometimes you may want to help simplify the client development work by including pagination information -directly in the response body. To do so, configure the [[yii\rest\Serializer::collectionEnvelope]] property -as follows: ```php use yii\rest\ActiveController; @@ -106,7 +105,7 @@ class UserController extends ActiveController } ``` -You may then get the following response for request `http://localhost/users`: +Тогда вы можете получить следующий ответ на запрос `http://localhost/users`: ``` HTTP/1.1 200 OK From ede4d8ee5ff6bacd5a3cebd04fa9a2cdc5a6964b Mon Sep 17 00:00:00 2001 From: Dmitry Korolev Date: Sun, 31 Aug 2014 15:18:15 +0400 Subject: [PATCH 3/4] small translation fixes --- docs/guide-ru/rest-response-formatting.md | 27 ++++++++++++----------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/docs/guide-ru/rest-response-formatting.md b/docs/guide-ru/rest-response-formatting.md index 5f118d8960..10b6defd72 100644 --- a/docs/guide-ru/rest-response-formatting.md +++ b/docs/guide-ru/rest-response-formatting.md @@ -4,26 +4,26 @@ При обработке RESTful API запросов приложение обычно выполняет следующие шаги, связанные с форматированием ответа: 1. Определяет различные факторы, которые могут повлиять на формат ответа, такие как media type, язык, версия и т.д. - Этот процесс также известен как [обсуждение содержимого](http://en.wikipedia.org/wiki/Content_negotiation). + Этот процесс также известен как [согласование содержимого](http://en.wikipedia.org/wiki/Content_negotiation). 2. Конвертирует объекты ресурсов в массивы, как описано в секции [Ресурсы](rest-resources.md). Это задача для [[yii\rest\Serializer]]. -3. Конвертирует массивы в строке в формате, определенном на этапе обсуждения содержимого. Это задача для +3. Конвертирует массивы в строке в формате, определенном на этапе согласование содержимого. Это задача для [[yii\web\ResponseFormatterInterface|форматера ответов]], регистрируемого с помощью компонента приложения [[yii\web\Response::formatters|response]]. -## Обсуждение содержимого +## Согласование содержимого -Yii поддерживает обсуждение содержимого с помощью фильтра [yii\filters\ContentNegotiator]]. Базовый класс +Yii поддерживает согласование содержимого с помощью фильтра [yii\filters\ContentNegotiator]]. Базовый класс контроллера RESTful API [[yii\rest\Controller]] использует этот фильтр под именем `contentNegotiator`. -Фильтр обеспечивает соответствие формата ответа и определение языка. Например, если RESTful API запрос +Фильтр обеспечивает соответствие формата ответа и определяет используемый язык. Например, если RESTful API запрос содержит следующий заголовок: ``` Accept: application/json; q=1.0, */*; q=0.1 ``` -Он будет получать ответ в формате JSON следующего вида: +Он будет получать ответ в JSON-формате следующего вида: ``` $ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users" @@ -59,11 +59,11 @@ Content-Type: application/json; charset=UTF-8 [[yii\filters\ContentNegotiator]] проверит HTTP-заголовок `Accept` в запросе и установит, что [[yii\web\Response::format|формат ответа]] должен быть в `'json'`. После того, как экшн будет выполнен и вернет результирующий объект ресурса или коллекцию, [[yii\rest\Serializer]] конвертирует результат в массив. -И, наконец, [[yii\web\JsonResponseFormatter]] сериализует массив в строку JSON и включит ее в тело ответа. +И, наконец, [[yii\web\JsonResponseFormatter]] сериализует массив в строку в формате JSON и включит ее в тело ответа. По умолчанию, RESTful APIs поддерживает и JSON, и XML форматы. Для того, чтобы добавить поддержку нового формата, вы должны установить свою конфигурацию для свойства [[yii\filters\ContentNegotiator::formats|formats]] у фильтра -`contentNegotiator`, похожую на следующие классы контроллеров API: +`contentNegotiator`, например, с использованием поведения такого вида: ```php use yii\web\Response; @@ -84,12 +84,13 @@ public function behaviors() Как уже описано выше, [[yii\rest\Serializer]] - это центральное место, отвечащее за конвертацию объектов ресурсов или коллекций в массивы. Он реализует интерфейсы [[yii\base\ArrayableInterface]] и [[yii\data\DataProviderInterface]]. -[[yii\base\ArrayableInterface]] реализуется для объектов ресурсов, а [[yii\data\DataProviderInterface]] - для коллекций. +Для объектов ресурсов как правило реализуется интерфейс [[yii\base\ArrayableInterface]], а для коллекций - +[[yii\data\DataProviderInterface]]. -Вы можете переконфигурировать сереализатор с помощью настройки свойства [[yii\rest\Controller::serializer]], используя -конфигурационный массив. Например, иногда вам может быть нужно помочь упростить разработку на клиенте с помощью -добавления информации о пагинации непосредственно в тело ответа. Чтобы сделать это, переконфигурируйте свойство -[[yii\rest\Serializer::collectionEnvelope]] следующим образом: +Вы можете переконфигурировать сериализатор с помощью настройки свойства [[yii\rest\Controller::serializer]], используя +конфигурационный массив. Например, иногда вам может быть нужно помочь упростить разработку клиентской части +приложения с помощью добавления информации о пагинации непосредственно в тело ответа. Чтобы сделать это, +переконфигурируйте свойство [[yii\rest\Serializer::collectionEnvelope]] следующим образом: ```php From bef6a759c7cc17ad7f34bb7ef7d42328653b0763 Mon Sep 17 00:00:00 2001 From: Dmitry Korolev Date: Mon, 1 Sep 2014 11:33:15 +0400 Subject: [PATCH 4/4] another small translation fixes --- docs/guide-ru/rest-response-formatting.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/guide-ru/rest-response-formatting.md b/docs/guide-ru/rest-response-formatting.md index 10b6defd72..8d2f30adf8 100644 --- a/docs/guide-ru/rest-response-formatting.md +++ b/docs/guide-ru/rest-response-formatting.md @@ -6,8 +6,8 @@ 1. Определяет различные факторы, которые могут повлиять на формат ответа, такие как media type, язык, версия и т.д. Этот процесс также известен как [согласование содержимого](http://en.wikipedia.org/wiki/Content_negotiation). 2. Конвертирует объекты ресурсов в массивы, как описано в секции [Ресурсы](rest-resources.md). - Это задача для [[yii\rest\Serializer]]. -3. Конвертирует массивы в строке в формате, определенном на этапе согласование содержимого. Это задача для + Этим занимается [[yii\rest\Serializer]]. +3. Конвертирует массивы в строки исходя из формата, определенного на этапе согласование содержимого. Это задача для [[yii\web\ResponseFormatterInterface|форматера ответов]], регистрируемого с помощью компонента приложения [[yii\web\Response::formatters|response]]. @@ -15,7 +15,7 @@ ## Согласование содержимого Yii поддерживает согласование содержимого с помощью фильтра [yii\filters\ContentNegotiator]]. Базовый класс -контроллера RESTful API [[yii\rest\Controller]] использует этот фильтр под именем `contentNegotiator`. +контроллера RESTful API - [[yii\rest\Controller]] - использует этот фильтр под именем `contentNegotiator`. Фильтр обеспечивает соответствие формата ответа и определяет используемый язык. Например, если RESTful API запрос содержит следующий заголовок: @@ -23,7 +23,7 @@ Yii поддерживает согласование содержимого с Accept: application/json; q=1.0, */*; q=0.1 ``` -Он будет получать ответ в JSON-формате следующего вида: +Он получит ответ в JSON-формате такого вида: ``` $ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users" @@ -55,13 +55,13 @@ Content-Type: application/json; charset=UTF-8 ] ``` -Под копотом происходит следующее: прежде, чем экшн RESTful API контроллера будет выполнен, фильтр +Под копотом происходит следующее: прежде, чем *действие* RESTful API контроллера будет выполнено, фильтр [[yii\filters\ContentNegotiator]] проверит HTTP-заголовок `Accept` в запросе и установит, что -[[yii\web\Response::format|формат ответа]] должен быть в `'json'`. После того, как экшн будет выполнен и вернет -результирующий объект ресурса или коллекцию, [[yii\rest\Serializer]] конвертирует результат в массив. +[[yii\web\Response::format|формат ответа]] должен быть в `'json'`. После того, как *действие* будет выполнено и вернет +итоговый объект ресурса или коллекцию, [[yii\rest\Serializer]] конвертирует результат в массив. И, наконец, [[yii\web\JsonResponseFormatter]] сериализует массив в строку в формате JSON и включит ее в тело ответа. -По умолчанию, RESTful APIs поддерживает и JSON, и XML форматы. Для того, чтобы добавить поддержку нового формата, +По умолчанию, RESTful API поддерживает и JSON, и XML форматы. Для того, чтобы добавить поддержку нового формата, вы должны установить свою конфигурацию для свойства [[yii\filters\ContentNegotiator::formats|formats]] у фильтра `contentNegotiator`, например, с использованием поведения такого вида: @@ -82,7 +82,7 @@ public function behaviors() ## Сериализация данных -Как уже описано выше, [[yii\rest\Serializer]] - это центральное место, отвечащее за конвертацию объектов ресурсов +Как уже описывалось выше, [[yii\rest\Serializer]] - это центральное место, отвечащее за конвертацию объектов ресурсов или коллекций в массивы. Он реализует интерфейсы [[yii\base\ArrayableInterface]] и [[yii\data\DataProviderInterface]]. Для объектов ресурсов как правило реализуется интерфейс [[yii\base\ArrayableInterface]], а для коллекций - [[yii\data\DataProviderInterface]].