symfony1.4で国際化してみる
symfony1.4で国際化の手順
まずは言語の管理
symfonyにはユーザカルチャというものが存在しており、そこに言語の種類を入れます
$this->getUser()->setCulture('ja'); echo $this->getUser()->getCulture();
デフォルトの言語を設定する
// apps/frontend/config/setting.yml all: .settings: default_culture: ja
※注意すべきは、symfonyのキャッシュだけでなくブラウザのキャッシュにもcultureが残ること。言語を変更した場合は必ずブラウザのキャッシュもクリアすること
URLを国際化に対応させる。
homepageを除く全てのルーティングにsf_cultureを加える
default_index: url: /:module param: { action: index }
を
default_index: url: /:sf_culture/:module param: { action: index }
上記のように追加していきます
さらに、多言語のトップページを作るために
routing.ymlに以下を追記
localized_homepage: url: /:sf_culture/ param: { module: default, action: index } requirements: sf_culture: (?:ja|en)
sf_culture: (?:ja|en)
この部分は日本語と英語以外は受け付けないというのを記述している
myUserに以下のメソッドを追記
// apps/frontend/lib/myUser.class.php public function isFirstRequest($boolean = null) { if (is_null($boolean)) { return $this->getAttribute('first_request', true); } $this->setAttribute('first_request', $boolean); }
実際の使い方
// apps/frontend/modules/hogehoge/actions/actions.class.php public function executeIndex(sfWebRequest $request) { if (!$request->getParameter('sf_culture')) { if ($this->getUser()->isFirstRequest()) { $culture = $request->getPreferredCulture(array('ja', 'en')); $this->getUser()->setCulture($culture); $this->getUser()->isFirstRequest(false); } else { $culture = $this->getUser()->getCulture(); } $this->redirect('localized_homepage'); } }
ユーザカルチャがない場合はその言語のホームに飛ぶようになってます