From abbdf10c0393a17a084849640a284e0d07e2af61 Mon Sep 17 00:00:00 2001 From: Dmitry Korolev Date: Sun, 31 Aug 2014 15:08:07 +0400 Subject: [PATCH] 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 68badfc..5f118d8 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