4

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.

rafaelphp
  • 279
  • 2
  • 11
  • Did you look this http://stackoverflow.com/questions/38293988/zf3-zend-mvc-skeleton-internationalization-not-working – hkulekci Sep 01 '16 at 13:48
  • Thanks for reply, but translate on view I already config and is working fine, I need translate on controller. – rafaelphp Sep 01 '16 at 14:39

2 Answers2

2

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.

Community
  • 1
  • 1
Wilt
  • 41,477
  • 12
  • 152
  • 203
  • Hi, I create a plugin called translate, and inject into the serviceManager, then inside the plugin I get the global MvcTranslator, and work fine. but thanks. One question is that right on your configuration using the View\Helper\Translate::class as plugin? – rafaelphp Dec 21 '16 at 18:12
2

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');
J.Ewa
  • 205
  • 3
  • 14