When the [[formats|supported formats]] property is specified, ContentNegotiator will support response format
negotiation based on the value of the GET parameter [[formatParam]] and the Accept HTTP header.
If a match is found, the [[Response::format]] property will be set as the chosen format.
The [[Response::acceptMimeType]] as well as [[Response::acceptParams]] will also be updated accordingly.
When the [[languages|supported languages]] is specified, ContentNegotiator will support application
language negotiation based on the value of the GET parameter [[languageParam]] and the Accept-Language HTTP header.
If a match is found, the [[\yii\base\Application::language]] property will be set as the chosen language.
You may use ContentNegotiator as a bootstrapping component as well as an action filter.
The following code shows how you can use ContentNegotiator as a bootstrapping component. Note that in this case,
the content negotiation applies to the whole application.
php
in application configuration
use yii\web\Response;
return [
'bootstrap' => [
[
'class' => 'yii\filters\ContentNegotiator',
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
'languages' => [
'en',
'de',
],
],
],
];
The following code shows how you can use ContentNegotiator as an action filter in either a controller or a module.
In this case, the content negotiation result only applies to the corresponding controller or module, or even
specific actions if you configure the only or except property of the filter.
php
use yii\web\Response;
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index'], // in a controller
if in a module, use the following IDs for user actions
'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
'languages' => [
'en',
'de',
],
],
];
}