在我的ZF2系统中使用语言切换器的最佳选择是什么?

时间:2016-01-26 03:53:25

标签: php localization zend-framework2 zend-translate

我为我的一个客户开发了小型ZF2学说系统。到目前为止一切都很好,但他们需要2种语言的系统。

我可以将默认语言设置为englishanother language module/Application/config/module.config.php

'translator' => array(
    'locale' => 'en_US',
    'translation_file_patterns' => array(
        array(
            'type'     => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.mo',
        ),
    ),
),

我也可以使用此方法在module.php

中设置默认值
public function onBootstrap(MvcEvent $e)
{
    $application = $e->getApplication();
    $serviceManager = $application->getServiceManager();
    // Just a call to the translator, nothing special!
    $serviceManager->get('translator');
    $this->initTranslator($e);

    // Etc, more of your bootstrap function.
}

protected function initTranslator(MvcEvent $event)
{
    $serviceManager = $event->getApplication()->getServiceManager();

    // Zend\Session\Container
    $session = New Container('language');

    $translator = $serviceManager->get('translator');
    $translator
        ->setLocale($session->language)
        ->setFallbackLocale('zh_CN')
        ;


}

这很好,现在我的系统显示默认语言为中文。但是,我想让用户可以选择。

我该怎么做?

我找到了这个link,但我无法让它发挥作用。

当我在Application/IndexController.php中添加以下功能时,它不做任何事情而是http://myurl.com/changeLocal抛出404 error。我是否还需要在module.config.php中添加任何内容?

public function changeLocaleAction() 
{
    // New Container will get he Language Session if the SessionManager already knows the language session.
    $session = new Container('language');
    $language = $request->getPost()->language;
    $config = $this->serviceLocator->get('config');
    if (isset($config['locale']['available'][$language])) {
        $session->language = $language;
        $this->serviceLocator->get('translator')->setLocale($session->language);
    }
}

2 个答案:

答案 0 :(得分:2)

您需要一些方法来调用changeLocaleAction。连接到此控制器操作的路径确实是最简单的:

'language' => array(
    'type' => 'literal',
    'options' => array(
        'route' => '/language',
        'defaults' => array(
            'controller' => `Application\Controller\IndexController`,
            'action' => 'changeLocaleAction'
        )
    )
),

您需要在方法中捕获语言的后置值:

$request->getPost('language');

或者在你的控制器中使用params插件:

$this->params()->fromPost('language');

因此,这表示用户发布了一个包含language字段的表单,其中包含首选语言设置,例如'zh_CN''en_US'作为值。

您可以简化客户端,因为您只有两种语言选项。您只需使用切换语言的按钮并发布其他值:

因此,如果当前语言为'en_US',则您发布'zh_CN',反之亦然。

答案 1 :(得分:2)

经过长时间的战斗,我就是这样做的。特别感谢@Kwido @Wilt 让我向正确的方向发送(我已将它们都投了出去)。

<强>应用/配置/ module.config.php

return array(
    'controllers' => array(
        'invokables' => array(
            'Application\Controller\Index' => 'Application\Controller\IndexController'
        ),
    ),
    'router' => array(
        'routes' => array(
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
            ),

            'language' => array(
                'type' => 'Segment',
                'options' => array(
                    //'route' => '/[:language]',
                    'route' => '/en',
                    'constraints' => array(
                        'language' => 'en',
                    ),
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action' => 'changeLocaleEnglish'
                    )
                )
            ),
            'languageChinese' => array(
                'type' => 'Segment',
                'options' => array(
                    //'route' => '/[:language]',
                    'route' => '/cn',
                    'constraints' => array(
                        'language' => 'cn',
                    ),
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action' => 'changeLocaleChinese'
                    )
                )
            ),
            ////
            // other stuff
            //////////// like child routes etc
        ),
    ),
    'service_manager' => array(
        'abstract_factories' => array(
            'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
            'Zend\Log\LoggerAbstractServiceFactory',
        ),
        'factories' => array(
            'translator' => 'Zend\Mvc\Service\TranslatorServiceFactory',
        ),
    ),

    'translator' => array(
        'locale' => 'zh_CN', //default is english which is set in module.php
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),

    'view_helpers' => array(
        'invokables'=> array(
            'PaginationHelper' => 'Application\View\Helper\PaginationHelper'
        )
    ),

    'view_manager' => array(
        //....... view stuff
    ),
    // Placeholder for console routes
    'console' => array(
        'router' => array(
            'routes' => array(
            ),
        ),
    ),
);

<强>应用/ module.php

public function onBootstrap(MvcEvent $e)
{
    $application = $e->getApplication();
    $serviceManager = $application->getServiceManager();
    // Just a call to the translator, nothing special!
    $serviceManager->get('translator');
    $this->initTranslator($e);
}

protected function initTranslator(MvcEvent $event)
{
    $serviceManager = $event->getApplication()->getServiceManager();

    // use Zend\Session\Container add this to top
    $session = New Container('language');

    $translator = $serviceManager->get('translator');
    if($session['language'] != 'zh_CN'){ //if session doesn't have zh_CN then set it as english
    $translator
        ->setLocale($session->language)
        ->setFallbackLocale('en_US')
        ;
    }
}

现在在 Application / src / Application / Controller / IndexController.php 我添加了两个操作来捕获会话并设置语言:

public function changeLocaleChineseAction() 
    {
        $result = new ViewModel();
        $result->setTerminal(true);
        $response = $this->getResponse();


        // New Container will get he Language Session if the SessionManager already knows the language session.
        $session = new Container('language');
        $request = $this->getRequest();
        $config = $this->serviceLocator->get('config');

        $language = $config['translator']['locale']; //default locale from Application/config/module.config.php
        if (isset($config['translator']['locale'])) {
            $session->language = $language;
            $this->serviceLocator->get('translator')->setLocale('zh_CN')
                ->setFallbackLocale('zh_CN')
                ;

        }

        return $this->redirect()->toRoute('home'); 

    }

    public function changeLocaleEnglishAction() 
    {
        // New Container will get he Language Session if the SessionManager already knows the language session.
        $session = new Container('language');

        //just clear the language session
        $session->getManager()->getStorage()->clear('language');
        $language = 'en_US'; //set new language
        $request = $this->getRequest();
        $config = $this->serviceLocator->get('config');
        $session->language = $language;
        $this->serviceLocator->get('translator')->setLocale('en_US')
            ->setFallbackLocale('en_US')
            ;
        return $this->redirect()->toRoute('home');

    }

现在只需添加layout.phtml中的链接即可拥有语言切换器:

<a href="<?php echo $this->url('home')."cn";?>"><?php echo $this->translate("Chinese");?></a>
<a href="<?php echo $this->url('home')."en";?>"><?php echo $this->translate("English");?></a>

希望将来能有所帮助。