Search code examples
controllertranslationzend-framework2

ZF2 use translator in controller


For a url redirection I need to translate something in the controller.

How can I acces $this->translate(); in the controller?

Thanks! Nick


Solution

  • Translation is done via a Translator. The translator is an object and injected for example in a view helper, so if you call that view helper, it uses the translator to translate your strings. For this answer I assume you have configured the translator just the same as the skeleton application.

    The best way is to use the factory to inject this as a dependency into your controller. The controller config:

    'controllers' => array(
      'factories' => array(
        'my-controller' => function($sm) {
          $translator = $sm->getServiceLocator()->get('translator');
          $controller = new MyModule\Controller\FooController($translator);
        }
      )
    )
    

    And the controller itself:

    namespace MyModule;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\I18n\Translator\Translator;
    
    class FooController extends AbstractActionController
    {
      protected $translator;
    
      public function __construct(Translator $translator)
      {
        $this->translator = $translator;
      }
    }
    

    An alternative is to pull the translator from the service manager in your action, but this is less flexible, less testable and harder to maintain:

    public function fooAction()
    {
      $translator = $this->getServiceManager()->get('translator');
    }
    

    In both cases you can use $translator->translate('foo bar baz') to translate your strings.