How to get translator inside controller plugin on ZF3

4.3k views Asked by At

I want to create a plugin to use zend-i18n/translate on controller. On zf2 I have a controller plugin that does this for me, but on zf3 I could not get this to work. How can I use zend-i18n inside a controller or via controller plugin with zf3?

========== I just found what I need here on zf doc: https://docs.zendframework.com/zend-mvc-i18n/services/#mvctranslator-and-translatorfactory

if you already have config the translator as factory on your module.config.php, you can inject on your controller plugin.

2

There are 2 answers

1
Wilt On BEST ANSWER

You can virtually do the same as the answer that @hkulekci referred to in his comment.

'service_manager' => [
    'factories' => [
        \Zend\I18n\Translator\TranslatorInterface::class => \Zend\I18n\Translator\TranslatorServiceFactory::class,
    ]
]

and

'controller_plugins' => [
    'invokables' => [
        'translate' => \Zend\I18n\View\Helper\Translate::class
    ]
]

After that you can get the translate plugin like in your controller action methods like this:

public someAction(){
    $translator = $this->translate;
}

Check the Zend Framework documentation or this Zend Framework blog for more details on the controller plugin manager.

0
J.Ewa On

For translate in model and controller, I did this in my module.config.php

'service_manager' => [
    'factories' => [
        \Zend\I18n\Translator\Translator::class => \Zend\I18n\Translator\TranslatorServiceFactory::class,
    ],
],

Then from my controller or model which has serviceContainer initialised I do:

$this->myVar = $serviceContainer->get(\Zend\I18n\Translator\Translator::class);

Then I can access it by doing

$this->myVar->translate('lorem ipsum');