ZF2 Translate in Controller

If you want to

use the translator in controller like in view, just like that:


instead of ugly:


You have to write own controller plugin, just like view helper Zend\I18n\View\Helper\Translate.
Of course, you can invoke the plugin with the same signature:
__invoke($message, $textDomain = null, $locale = null)

To register a new plugin, put these lines in your configuration module.config.php:

'controller_plugins' => array(
    'factories' => array(
        'translate' => 'Application\Controller\Plugin\Translate',

Now, create your own plugin:

< ?php

namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;

use Zend\I18n\Translator\Translator;

class Translate implements FactoryInterface
    public function createService(ServiceLocatorInterface $serviceLocator)
        $serviceLocator = $serviceLocator->getController()->getServiceLocator();
        $serviceFactory = new TranslatorServiceFactory();
        $translator = $serviceFactory->createService($serviceLocator);
        return new TranslatorProxy($translator);

final class TranslatorProxy extends AbstractPlugin
    private $translator;
public function __construct(Translator $translator) { $this->translator = $translator; } public function __invoke($message, $textDomain = 'default', $locale = null) { return $this->translator->translate($message, $textDomain, $locale); } public function __call($method, $args) { return call_user_func_array([$this->translator, $method], $args); } public static function __callstatic($method, $args)
{ return call_user_func_array([$this->translator, $method], $args); } }

How it works?

You see, the ServiceLocator passed in

createService(ServiceLocatorInterface $serviceLocator)

factory in configuration space controller_plugins, does have no access to the Config service in ServiceLocator in controller. So you cannot get the configuration and create the Translate object via TranslatorServiceFactory.

Instead of that, you can access to the ServiceLocator assigned to the controller for which our helper has been invoked, by typing $serviceLocator->getController().

Of course, $serviceLocator passed in createService method is instance of Zend\Mvc\Controller\PluginManager.

Why proxy?

The object returned via plugin factory has to implement


which is abstractly implemented in


so we created proxy object to forward all calls from our plugin to the Translate object.

Hope it helped!