CodeIgniter框架URL多语种实现

网上实现方式最多的是采用hooks:即在pre_controller挂勾点,做一个hooks处理,从url中获取出语言段

但是当我在使用该方法的时候,却遇到了不少问题,因为我做了HMVC扩展,可能是因为这个原因,使得hooks总是报错,于是我改成了以下思路:

1、开启URL重写

    1)修改application/config/config.php

   

$config['index_page'] = "";
$config['uri_protocol'] = "AUTO"

   2)修改php.ini

  

cgi.fix_pathinfo = 0

   3)开启apache的url重写模块

   4)在项目根目录新建.htaccess文件,内容如下:

  

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/system.*
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?/$1 [L]

   5)重启apache

2、修改application/config/routes.php,新增后边两行

   

$route['default_controller'] = "home";
$route['404_override'] = '';

//定义语言选择路由
$route['(en)(:any)'] = "$2";
$route['en'] = "home";

3、在application/core/下新建MY_Controller类并继承自CI_Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
 function __construct(){
	 parent::__construct();
		$my_lang = $this->uri->segment(1);
		$this->config->set_item('lang_path','');
		//默认语言为中文Chinese
		if ($my_lang=='en')
		{
			//动态设置当前语言为'en'
			$this->config->set_item('language', $my_lang);
			//将语言段自动配置到url
			$this->config->set_item('lang_path',$my_lang.'/');
		}
		$this->load->helper('language');
	  }
 }

4、所有需要用到判别language的控制器,均继承自我自己创建的MY_Controller类

class User extends MY_Controller

 5、在控制器中加载语言文件,如:加载application/languages/en/error_lang.php

$this->lang->load('error');
$errmsg = array(
	'error' => lang('error_login_failed')
);

 6、在对应的语言模板中输出

  

<?=$error?>

 7、地址栏输入:

     yourwebsite/en 显示英文模板

     yourwebsite/     显示默认语言模板 默认语言模板在application/config/config.php 配置$config['language']项即可

8、完成

猜你喜欢

转载自57pm.iteye.com/blog/1856300