Yii2 RESTful: 内容协商语言不起作用

Yii2 RESTful: Content Negotiation languages not work

我用 Yii2 中的模型实现了 API 的结构。一切都适用于操作(索引、创建、更新等...)和方法(GET、POST、PUT 等..),但我对 ContentNegotiator class 有疑问。 具体来说,如果我将要翻译响应的语言作为 GET 的参数传递,则会被忽略。 根据设置响应语言的文档,我们需要设置 ContentNegotiator 允许的语言(看我的 behaviors())并发出这样的请求:

http://localhost/api/v1/users?_lang=it-IT

但回复仍然是英文。为什么???不反对英语 =)

这是我的 ActiveController child class 延伸自 yii\rest\Controller.

use yii\rest\ActiveController;
use yii\filters\VerbFilter;

class AActiveController extends ActiveController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['verbFilter'] = [
            'class' => VerbFilter::className(),
            'actions' => $this->verbs(),
        ];
        $behaviors['contentNegotiator']['languages'] = [
            'en-EN',
            'it-IT',
            'de-DE',
            'ru-RU',
        ];

        return $behaviors;
    }
...

N.B.:我通过框架的 yii\filters\ContentNegotiator class 进行调试,此时应用程序语言设置正确但回复始终为英文。

negotiate() public method

public function negotiate()
{
    $request = $this->request ?: Yii::$app->getRequest();
    $response = $this->response ?: Yii::$app->getResponse();
    if (!empty($this->formats)) {
        $this->negotiateContentType($request, $response);
    }
    if (!empty($this->languages)) {
        Yii::$app->language = $this->negotiateLanguage($request);
    }
    debug(Yii::$app->language); // result OK!: it-IT 
}

看起来有些内置错误没有翻译,例如 yii\rest\Action:103 抛出 throw new NotFoundHttpException("Object not found: $id") 它没有翻译。你有不同的方法来解决这个问题:

  1. 好方法。扩展此操作并使用 translate
  2. 抛出正确的异常
  3. 糟糕的方式。编辑框架文件本身。
  4. 最好的方法。为框架创建补丁并发送给维护者。

有关 i18n 的更多信息see documentation