Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering custom Translator Loader in Zend Framework 2

I'm trying to register a custom database translator loader.

For that i was inspired by: Feeding Zend Translator

I have the following facotry code in (module.config.php):

'service_manager' => array(
    'factories' => array(
        'translator' => function($sm){
            $translator = new \V1\Service\DatabaseTranslationService();
            return $translator->createService($sm);
        },
    ),
),

The DatabaseTranslationService looks like that:

$config = $serviceLocator->get('Config');
    $trConfig = isset($config['translator']) ? $config['translator'] : array();
    $translator = new \Zend\I18n\Translator\Translator();
    $translator->getPluginManager()->setInvokableClass('database', '\Foo\I18n\Translator\Loader\DatabaseTranslator', true);
    $translator->addTranslationFile('database', 'en_EN');

    return $translator;

But it seems like "setInvokableClass" isn't used: I got this error:

Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for database

Does anybody know how to registering the Translator correctly

like image 934
MadeOfSport Avatar asked Oct 25 '12 19:10

MadeOfSport


2 Answers

After two days of search I've found a solution.

I don't know if it's a good solution, but it works for me.

Replace the line:

$translator->getPluginManager()->setInvokableClass('database', '\Foo\I18n\Translator\Loader\DatabaseTranslator', true);

with

$viewHelper = $serviceLocator->get('viewHelperManager');
$viewHelper->setInvokableClass('database', '\Foo\I18n\Translator\Loader\DatabaseTranslator', true);

I hope this solution helps you.

like image 126
Mathieu Avatar answered Oct 26 '22 23:10

Mathieu


In the current version (zf2 2.2.4) you only need to change the type-config entry:

'translator' => array(
    'locale' => 'de_DE',
    'translation_file_patterns' => array(
        array(
            'type' => 'YourNamespace\I18n\Translator\Loader\YourCustomFormat',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.whatever',
        ),
    ),
)

The YourNamespace\I18n\Translator\Loader\YourCustomFormat must implement the Zend\I18n\Translator\Loader\FileLoaderInterface interface; the load($locale, $filename) method must return a Zend\I18n\Translator\TextDomain instance.

This worked for me.

(of course the autoloader must find the class)

like image 37
MonkeyMonkey Avatar answered Oct 27 '22 01:10

MonkeyMonkey