CakePHP 3.x 本地化
为动态语言更改创建操作
路线
$routes->connect('/locale', ['controller' => ' Users', 'action' => 'languageChange']);
控制器动作
用户控制器
use Cake\Http\Session;
use Cake\I18n\I18n;
//Before filter in users controller
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
}
/**
* Change language
*/
public function languageChange()
{
if ($this->request->is('post')) {
$session = $this->getRequest()->getSession();
if (!empty($this->request->getData('locale'))) {
$session->write('Config.language', $this->request->getData('locale'));
$this->redirect($this->referer());
} else {
$session->write('Config.language', I18n::getLocale());
$this->redirect($this->referer());
}
}
}
创建视图文件意味着language_change.ctp文件
<?php
echo $this->Form->create("Localizations", array('url' => '/locale'));
echo $this->Form->radio("locale", [
['value' => 'en_US', 'text' => 'English'],
['value' => 'de_DE', 'text' => 'German'],
['value' => 'fr_FR', 'text' => 'French'],
]);
echo $this->Form->button('Change Language');
echo $this->Form->end();
?>
<h2><?php echo __('Hello'); ?></h2>
<h2><?php echo __('How are you?'); ?></h2>
<h2><?php echo __('Wel Come'); ?></h2>
<h2><?php echo __('Good Job'); ?></h2>
AppController
use Cake\I18n\I18n;
use Cake\Http\Session;
use Cake\Core\Configure;
public function beforeFilter(Event $event)
{
$session = $this->getRequest()->getSession();
if ($session->check('Config.language')) {
I18n::setLocale($session->read('Config.language'));
} else {
$session->write('Config.language', I18n::getLocale());
}
}
在文件中创建此位置
src/Locale/en_US/default.po
msgid "Hello"
msgstr "Hello"
msgid "How are you?"
msgstr "How are you?"
msgid "Wel Come"
msgstr "Wel Come"
msgid "Good Job"
msgstr "Good Job"
-
src/Locale/de_DE/default.po
msgid "Hello"
msgstr "Hallo"
msgid "How are you?"
msgstr "Hoe gaat het met je?"
msgid "Wel Come"
msgstr "Wel kom"
msgid "Good Job"
msgstr "Goed gedaan"
-
在 boostrap.php 中配置
'会话'=> [
'默认值' => 'php',
'语言' => 'en_US'
]