Below is what I have done so far -
In Application Module - module.config.php
-
'service_manager' => array(
[....],
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
In Album Module - module.config.php
-
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '[/:lang]/album[/:action][/:id]',
'constraints' => array(
'lang' => '[a-zA-Z]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
In Album Module - Module.php
-
public function onBootstrap(MvcEvent $e) {
$sm = $e->getApplication()->getServiceManager();
$router = $sm->get('router');
$request = $sm->get('request');
$matchedRoute = $router->match($request);
$params = $matchedRoute->getParams();
if(isset($params['lang']) && $params['lang'] !== '') {
$translator = $e->getApplication()->getServiceManager()->get('translator');
//or
//$translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
if($params['lang'] == 'en')
$translator->setLocale('en_US');
elseif($params['lang'] == 'fr')
$translator->setLocale('fr_FR');
else
$translator->setLocale('en_US');
}
}
In view
-
echo $this->translate('Home');
Note: URL - http://zf2-tutorial.localhost/fr/album
, works just fine. The translation is successful.
Query -
$translator->setLocale('en');
seems to be working with ZF1 but not with ZF2.
I need to know whether there is any way to directly set the URL param value like $translator->setLocale($params['lang']);
rather then long if-else
or switch
statements.
Some sites might be in 20 or more languages.
Thanks in advance.