zend-framework3zend-controller-plugin

How to get translator inside controller plugin on ZF3


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.


Solution

  • 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.