$locale = new Zend_Locale('auto');
$lang = $locale->getLanguage();
; allowed locales (first locale - default)
locales.uk = uk_UA
locales.ru = ru_RU
locales.en = en_GB
$locales = $config->locales->toArray();
$locale = new Zend_Locale('auto');
$lang = array_key_exists($locale->getLanguage(), $locales)
? $locale->getLanguage() : $config->locales->key();
// change default router
$frontController->getRouter()->addRoute('default',
new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
'lang' => $lang
)
)
);
// add multilingual route
$frontController->getRouter()->addRoute('default_multilingual',
new Zend_Controller_Router_Route(
':lang/:module/:controller/:action/*',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
'lang' => $lang
),
array(
'lang' => '\w{2}'
)
)
);
<?php
class Site_Controller_Action_Helper_Language extends Zend_Controller_Action_Helper_Abstract {
protected $_sDefaultLanguage;
protected $_aLocales;
protected $_sLanguagesDirectoryPath;
/**
* @param array $aLocales - Available locales
* @param string $sLanguagesDirectoryPath
*/
public function __construct(array $aLocales, $sLanguagesDirectoryPath) {
$this->_sLanguagesDirectoryPath = $sLanguagesDirectoryPath;
$this->_aLocales = $aLocales;
$this->_sDefaultLanguage = key($aLocales); // get first language
}
public function init() {
// try get current language from url
$sLang = $this->getRequest()->getParam('lang');
if(! array_key_exists($sLang, $this->_aLocales)) {
$sLang = $this->_sDefaultLanguage;
}
// generate path to the gettext language file
$sLanguageFilePath = $this->_sLanguagesDirectoryPath . '/'. $sLang . '/LC_MESSAGES/' . $sLang . '.mo';
if(! file_exists($sLanguageFilePath)) {
$sLanguageFilePath = $this->_sLanguagesDirectoryPath . '/' . $this->_sDefaultLanguage . '/LC_MESSAGES/' . $this->_sDefaultLanguage . '.mo';
$sLang = $this->_sDefaultLanguage;
}
// get current locale by current language
$sLocale = $this->_aLocales[$sLang];
// setup translate object
$oTranslate = new Zend_Translate('gettext', $sLanguageFilePath, $sLang);
Zend_Form::setDefaultTranslator($oTranslate); // translated Zend_Form
$this->_actionController->_locale = $sLocale;
$this->_actionController->_lang = $sLang;
$this->_actionController->_translate = $oTranslate;
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->view->locale = $sLocale;
$viewRenderer->view->lang = $sLang;
$viewRenderer->view->translate = $oTranslate;
}
}
$languageHelper = new Site_Controller_Action_Helper_Language($locales, APPLICATION_PATH . '/languages');
Zend_Controller_Action_HelperBroker::addHelper($languageHelper);
Source: https://habr.com/ru/post/42495/
All Articles