在不帶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