我希望用户可以更改网站的语言。在Module.php中我写了这个:
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'bootstrapSession'), 10);
$config = $this->getConfig();
\Locale::setDefault('de');
\Zend\Validator\AbstractValidator::setDefaultTranslator(
$e->getApplication()
->getServiceManager()
->get('translator')
);
if ($session->language !== NULL)
{
$e->getApplication()->getServiceManager()->get('translator')->setLocale($session->language);
}
public function bootstrapSession()
{
$config = $this->getConfig();
$sessionConfig = new Session\Config\SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new Session\SessionManager($sessionConfig);
$sessionManager->start();
var_dump($sessionManager);
Session\Container::setDefaultManager($sessionManager);
}
public function getServiceConfig()
{
var_dump('halloo');
return array(
'factories' => array(
'session' => function() {
$session = Session\Container::getDefaultManager()->getStorage();
return $session;
},
),
);
}
在IndexController.php中,我想更改语言并在模块中获取它。这样语言就会改变。 这是我的行动:
public function enAction()
{
$session = $this->getServiceLocator()->get('session');
$session->language = 'en';
return $this->redirect()->toRoute('home');
}
浏览器显示没有错误,但语言不会更改。有人看到错误并可以帮助我吗?
答案 0 :(得分:1)
public function onBootstrap(MvcEvent $e){
// session container
$sessionContainer = new \Zend\Session\Container('locale');
// test if session language exists
if(!$sessionContainer->offsetExists('mylocale')){
// if not use the browser locale
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$sessionContainer->offsetSet('mylocale', \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
}else{
$sessionContainer->offsetSet('mylocale', 'en_US');
}
}
// translating system
$translator = $serviceManager->get('translator');
$translator ->setLocale($sessionContainer->mylocale)
->setFallbackLocale('en_US');
$mylocale = $sessionContainer->mylocale;
只需更改控制器语言
即可/**
*
* @return \Zend\View\Model\ViewModel
*/
public function changelocaleAction(){
// disable layout
$result = new ViewModel();
$result->setTerminal(true);
// variables
$event = $this->getEvent();
$matches = $event->getRouteMatch();
$myLocale = $matches->getParam('locale');
$redirect = $matches->getParam('redirecturl', '');
// translate
$sessionContainer = new Container('locale');
switch ($myLocale){
case 'fr_FR':
break;
case 'en_US':
break;
default :
$myLocale = 'en_US';
}
$sessionContainer->offsetSet('mylocale', $myLocale);
// redirect
switch ($redirect){
case '':
$this->redirect()->toRoute('home');
break;
default :
$this->redirect()->toUrl(urldecode($redirect));
}
return $result;
}