Translating route segments with ZF's gettext adapter
I want to try out the route translations in Zend Framework, but I'm using the gettext adapter and the most tutorials have PHP translate adapter, so I'm having problems to make it work.
In the main Bootstrap.php I have the method in which I set the routes:
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$translator = Zend_Registry::get('Zend_Translate');
Zend_Controller_Router_Route::setDefaultTranslator($translator);
$routerRoute = new Zend_Controller_Router_Route('@about',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'about'
)
);
$router->addRoute('about', $routerRoute);
This works for /a开发者_JS百科bout
path.
I'll paste the code in which I set Zend_Translate, but it basically loads a *.mo
file depending on current session language:
$langParam = $this->getSessionLang();
$localeString = $languages[$langParam];
$locale = new Zend_Locale($localeString);
$moFilePath = $langFolder . $langParam . '.mo';
if (!file_exists($moFilePath)) {
throw new Zend_Exception('File does not exist: ' . $moFilePath);
}
$translate = new Zend_Translate(
array(
'adapter' => 'gettext',
'content' => $moFilePath,
'locale' => $locale,
'ignore' => array('.'), // ignore SVN folders
'disableNotices' => ('production' === APPLICATION_ENV) // disable notices in Production
)
);
Zend_Registry::set('Zend_Translate', $translate);
Zend_Registry::set('Zend_Locale' , $locale);
This, ofc, it's called prior
to routing.
My question: can gettext be used as a translation adapter for a route, because I can't figure out how can I catch the @about
string with, let's say, poEdit? It can? Hooray! How?
Well, my mo's were all messed up. So there's no problem with the code.
Here's how you edit your mo files so that the route can translate it (I'm presume you have your ZF i18n working - Translate, Locale and the like):
1. Remember this?
$routerRoute = new Zend_Controller_Router_Route('@about',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'about'
)
);
2. See that '@about' string? That's the soon-to-be-translated path. So how do you translate a string so that poEdit will catch it? Well, you don't; not with poEdit anyway. You manually edit the .po file
:
#ro.po
msgid "about"
msgstr "despre"
#en.po
msgid "about"
msgstr "about"
The msgid should match your path string (minus the '@' string, ofc).
3. Now go open your po file with poEdit. You'll see a new string (surprised, huh?). Compile this po
to get a new shiny mo
file that ZF can use.
4. Now my site.com/about
or site.com/despre
paths work.
More info here.
精彩评论