本文实例讲述了yii框架多语言站点配置方法。分享给大家供大家参考,具体如下:

这里假设我们要建立 中文/英文 切换的站点

1. 设置全局默认的语言

文件添加代码:protected/config/main.php

'language' => 'zh_cn',

2. 控制器根据用户选择动态切换语言

一般来说,我们所有的控制器都是继承于 protected/components/controller.php 这个类。因此,我们可以在
这个类里面进行语言的定义来影响当前的请求。

public function init()
{
  if(isset($_get['lang']) && $_get['lang'] != "")
  {
    yii::app()->language = $_get['lang'];
    yii::app()->request->cookies['lang'] = new chttpcookie('lang', $_get['lang']);
  }
  else if(!empty(yii::app()->request->cookies['lang']))
  {
    yii::app()->language = yii::app()->request->cookies['lang'];
  }
  else
  {
    $lang = explode(',',$_server['http_accept_language']);
    yii::app()->language = strtolower(str_replace('-', '_', $lang[0]));
  }
}

3. 页面提供切换语言选项

在公用的 layouts 头部,加入

<?php echo chtml::link('中文', yii::app()->createurl('/', array('lang' => 'zh_cn')));?>
<?php echo chtml::link('english', yii::app()->createurl('/', array('lang' => 'en_us')));?>

4. 多语言描述文字

//common是对应的语言文件,路径:protected/messages/zh_cn/common.php
yii::t('common', 'hello, world!');

5. 数据库内容多语言

假设我们有这样的数据表:

create table if not exists `news` (
  `id` int(10) unsigned not null auto_increment,
  `lang` varchar(4) not null default ‘en', /* 这个用来区分不同语言的内容 */
  `title` varchar(255) not null,
  `text` text not null,
  primary key (`id`)
);

在 model里面添加一些代码,可以根据当前语言加载不同语言的 news。

class news extends cactiverecord
{
  /**
   * 这里会在查询数据的时候,合并条件,根据当前语言查出数据
   *
   */
  public function defaultscope()
  {
    return array(
      'condition' => "lang=:lang",
      'params' => array(
        ':lang' => yii::app()->language,
      ),
    );
  }
  
  /**
   * 提供这个方法,作一个例子说明,可以指定加载哪个语言的数据
   *
   */
  public function lang($lang)
  {
    $this->getdbcriteria()->mergewith(array(
      'condition' => "lang=:lang",
      'params' => array(
        ':lang' => $lang,
      ),
    ));
    return $this;
  }
}

使用方法:

// 加载默认语言的数据。
$posts = post::model()->findall();
// get posts written in german
// 加载 en_us 语言的数据。
$posts = post::model()->lang('en_us')->findall();