使应用程序语言环境意识到(从URL获取语言环境)



我需要帮助获取请求语言环境代码。

我的理论是定义URL中的语言环境:

`http://localhost/en/services/web

对于语言环境(英语)

`http://localhost/fr/services/web

对于语言环境(法语)

and then extract the locale from the URL and have the routes still work

该值将在$lang变量

中替换it

这是我当前的Application Module Class中的代码:

public function onBootstrap(MvcEvent $e)
{
  $lang = 'it'; // this needs to reflect current request locale instead
  $request = $e->getApplication()->getServiceManager()->get('Request');
  $translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
  $translator->addTranslationFile("phparray",Pluto::path('language',"$lang.php"));
  $viewHelperManager = $e->getApplication()->getServiceManager()->get('ViewHelperManager');
  $viewHelperManager->get('translate')->setTranslator($translator);
}

My solution would be to have the variable $lang populated with the request locale和其余的URL部分与路由

我想也会对我的路线进行一些修改。

晚上好!

您正在使用ZF2还是3?我邀请您看看https://github.com/juriansluiman/slmlocale,它可以以适当的方式做到您要实现的目标(甚至更多)。我保证几个月前会努力使其与ZF3兼容,但找不到时间,所以我稍后会调查,但是如果您需要您的需求,则只需在ZF2中使用它

您想要的确切功能是(如果您不想在应用中添加新模块):

for ZF3:https://gist.github.com/itach1uchixa/6ec75b8f2af47a0b63e3e3f52f52f52fa0285a24

for zf2:https://gist.github.com/itach1uchixa/4840b004be2f2dcdcded19ec516e8aaaa6f1

ZF2的示例配置:

1步。将下面的行添加到您的service_manager config

'HttpRouter' => 'ApplicationFactoryLocalizedTreeRouteFactory'

2步。向您的活动经理注册侦听器

ApplicationListenerRouteListener

3步。您的Translator Config必须具有

的Locales键
'translator' => array(
    // this will be default locale of route
    'locale'  => 'en_US',
    // key must be locale that you want
    'locales' => array(
        'en_US' => 'English',
        'fr'    => 'French', 
        'ru_RU' => 'Russian'
     ),
),

步骤3是可选的,您可以更改路由工厂以使用另一种配置上面的配置将使您路由:

/your/route or en_US/your/route for English
/fr/your/route for French
/ru_RU/your/route for Russian

最新更新