TranslationServiceProvider

TranslationServiceProvider

我正在尝试以最简单的方式使用Silex TranslationServiceProvider,即

<?php
// web/index.php
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->register(new Silex\Provider\TranslationServiceProvider(), array(
  'locale'            => 'fr',
  'locale_fallbacks'  => array('en')
));

$app['translator.domains'] = array(
  'messages' => array(
    'en' => array('message_1' => 'Hello!'),
    'fr' => array('message_1' => 'Bonjour')
));

echo $app['translator']->trans('message_1');
// I get 'Hello!' (why ?)


似乎未考虑初始化TranslationServiceProvider时的'locale' => 'fr'行,唯一计数的参数是locale_fallbacks(当我将locale_fallbacks更改为'fr'时,该消息以法语显示)

有什么很简单的我想念的吗?

提前致谢

编辑

当我使用setLocale函数时,它仍然不起作用,并且似乎覆盖了locale_fallbacks

$app->register(new Silex\Provider\TranslationServiceProvider(), array(
  'locale_fallbacks'  => array('en')
));

$app['translator']->setLocale('fr');
echo $app['translator']->getLocale(); // returns 'fr' as expected

$app['translator.domains'] = array(
  'messages' => array(
    'en' => array('message_1' => 'Hello!'),
    'fr' => array('message_1' => 'Bonjour')
));

echo $app['translator']->trans('message_1');
// now returns 'message_1' (??)


我使用提供程序的方式有什么问题?

最佳答案

您必须设置语言环境,否则将使用后备:

$app['translator']->setLocale('fr');


我在$app->before()处理程序中设置语言环境:

$app->before(function(Request $request) use ($app) {
  // default language
  $locale = 'en';
  // quick and dirty ... try to detect the favorised language - to be improved!
  if (!is_null($request->server->get('HTTP_ACCEPT_LANGUAGE'))) {
    $langs = array();
    // break up string into pieces (languages and q factors)
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
      $request->server->get('HTTP_ACCEPT_LANGUAGE'), $lang_parse);
    if (count($lang_parse[1]) > 0) {
        foreach ($lang_parse[1] as $lang) {
            if (false === (strpos($lang, '-'))) {
                // only the country sign like 'de'
                $locale = strtolower($lang);
            } else {
                // perhaps something like 'de-DE'
                $locale = strtolower(substr($lang, 0, strpos($lang, '-')));
            }
            break;
        }
    }
    $app['translator']->setLocale($locale);
    $app['monolog']->addDebug('Set locale to '.$locale);
  }
});

10-08 09:28