Search code examples
zend-framework2zend-translate

make project multilingual with Zend/Translator


Good evening,

I want to add zend/translate to my project to show my webside in several languages. But there doesn't work anything. Here are the steps I done already:

In the module.config.php I looked if the translator is initialized:

...

'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',

...

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

...

In the Module.php in the Bootstrap I set the DefaultTranslator:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    \Locale::setDefault('de_DE');
    \Zend\Validator\AbstractValidator::setDefaultTranslator(
            $e->getApplication()
                    ->getServiceManager()
                    ->get('translator')
    );
}

But when I reload my webside there is a error like this:

 Catchable fatal error: Argument 1 passed to Zend\Validator\AbstractValidator::setDefaultTranslator() must be an instance of Zend\Validator\Translator\TranslatorInterface, instance of Zend\I18n\Translator\Translator given, called in C:\xampp\htdocs\pimp\module\Application\Module.php on line 28 and defined in C:\xampp\htdocs\pimp\vendor\zendframework\zendframework\library\Zend\Validator\AbstractValidator.php on line 472

I think there is something I've forgotten..

Can someone help me?

Thanks.


Solution

  • There is a odd part in Zend i18n that Zend\I18n\Translator\Translator is not compatible with other components. The Mvc Translator binds the Translator to the other parts. The Zend\Mvc\I18n\Translator extends the "normal" translator and then it implements the translator interface requested by the Zend\Validator component.

    So, create the Mvc Translator by using the MVC translator factory. Replace Zend\I18n\Translator\TranslatorServiceFactory with Zend\Mvc\Service\TranslatorServiceFactory.