The Zend\I18n
component is used to handle translations in Zend Framework 2 applications.
It includes the Translator, which is the main service, but also a view helper that consumes it and can be used to translate texts directly inside views.
The first thing we have to do is to define a translator top level configuration block, so that the Translator service can be properly created.
[
'translator' => [
'locale' => 'en_US',
'translation_file_patterns' => [
[
'base_dir' => __DIR__ . '/../languages/phpArray',
'type' => 'phpArray',
'pattern' => '%s.php',
],
[
'base_dir' => __DIR__ . '/../languages/gettext',
'type' => 'gettext',
'pattern' => '%s.mo',
],
],
],
]
The translator configuration has two elements.
The Translator service can handle multiple language files in different formats. Usually you will define a group of language files per module, and each module will have its own translator configuration. At runtime all of them will be merged and you will have something like the example, with multiple translation_file_patterns.
The Zend\Mvc
component registers a service with the key MvcTranslator, which is the one that consumes the translator top level configuration, but some other services will try to find a translator service.
To fix this problem we have to define a service alias like this.
[
'service_manager' => [
'aliases' => [
'translator' => 'mvctranslator',
],
]
]
The Zend Skeleton Application has this preconfigured.
You will usually want to translate messages in view templates. That can be easily done by using the translate()
view helper, which internally consumes the translator service.
Inside a view partial, just call it by passing the message you want it to translate and optionally the text domain and locale.
<label><?php echo $this->translate('Hello') ?></label>
<label><?php echo $this->translate('Hello', null, 'en_US') ?></label>
And that's it, you are now ready to use Zend\I18n
.