在不带ID的url中传递语言名称,与表中的languag_name列进行比较。
让我们假设你有网址:http://localhost/mediabox/home/box/en
控制器
<?php
# I wont write a controller but you should know how to do that, im also writing code as if you are just focusing on getting language.
public function box(/**pass in your other uri params as needed **/ $lang_name = 'en'){
#you could load this in the constructor so you dont have to load it each time, or in autoload.php if your using it site wide.
$this->load->model('lang_model', 'langModel');
#this example shows loading the library and running the function
$this->load->library('lang_library');
$this->lang_library->_getLang($lang);
#this example shows putting the getLang function inside the controller itsself.
self::_getLang($lang);
}
库/私有函数
<?php
private functon _getLang($lang = 'en'){
#run the query to retrieve the lang based on the lang_name, returns object of lang incl id
$lang = $this->langModel->getLang($lang_name);
if (!$lang){
die('language not found');
}else{
return $lang;
}
郎模型
<?php
public function getLang($lang_name = 'en'){
$this->db->where('lang_name', $lang_name);
$this->db->limit(1);
$q = $this->db->get('languages');
if ($q->mysql_num_rows > 0){
return $q->result();
}else{
return false;
}
}
然后你会有与之相关联的对象的变量,那么你可以简单地调用$lang->lang_name;
或$lang->lang_id;
会话存储
<?php
#you could call this in the beginning after using an ajax `$.post();` to retrieve the ID.. the easiest route though is whats above. I use this in my REST APIs
$this->session->set_userdata('lang', $lang);
尝试使用会话:http://codeigniter.com/user_guide/libraries/sessions.html – 2012-03-22 11:43:06
的问题是:“为什么不是一个变量我路过URL到我的控制器可见”。忽略会话,表单和AJAX的答案,因为他们试图回答一个没有问到的问题。谈话会话还假定您正试图实现站点范围内的本地化,而您的代码示例看起来并非如此。它看起来更像是显示库存,其中每个项目可能以多种语言提供。 – 2012-03-22 16:44:26