2011-11-22 77 views
2

我想在URL中的控制器段之前傳遞一些站點範圍的驗證變量。在CodeIgniter的控制器URI段之前傳遞變量

例子:

默認網址是:

www.mysite.com/controller/method/variable/ 

有時候我想有還URL這樣引用這個網站(題材,菜單的用戶創建子配置。 ..),所以用戶可以很好地分享這個網站的網址,其他人可以通過他的自定義配置來查看網站。

www.mysite.com/username/controller/method/variable 

這裏用戶名BASE_URL的定製部分。它應該根據數據庫進行驗證,並設置爲會話變量,以便稍後在我的控制器中使用它並更改主題。此網站的所有鏈接將開始使用www.mysite.com/username作爲base_url在網址與此用戶名在URL中輸入後。要解決這個

辦法之一是路由這樣的:

controller/method/variable_name1/variable_value1/user_conf/username 

...和實施在我的項目添加到每個單獨的控制器。但這不是一個優雅的解決方案。

回答

1

這個問題搞亂了一天我結束了添加自定義類路由器到我的項目之後。我在笨2.0工作,所以這個文件的位置應該是application/core/MY_Router.php

我的代碼如下:

class MY_Router extends CI_Router { 

// -------------------------------------------------------------------- 

/** 
* OVERRIDE 
* 
* Validates the supplied segments. Attempts to determine the path to 
* the controller. 
* 
* @access private 
* @param array 
* @return array 
*/ 
function _validate_request($segments) 
{ 
    if (count($segments) == 0) 
    { 
     return $segments; 
    } 

    // Does the requested controller exist in the root folder? 
    if (file_exists(APPPATH.'controllers/'.$segments[0].EXT)) 
    { 
     return $segments; 
    } 

    $users["username"] = 1; 
    $users["minu_pood"] = 2; 
    // $users[...] = ...; 
    // ... 
    // Basically here I load all the 
    // possbile username values from DB, memcache, filesystem, ... 
    if (isset($users[$segments[0]])) { 
     // If my segments[0] is in this set 
     // then do the session actions or add cookie in my cast. 
     setcookie('username_is', $segments[0], time() + (86400 * 7)); 
     // After that remove this segment so 
     // rounter could search for controller! 
     array_shift($segments); 
     return $segments; 
    } 

    // So segments[0] was not a controller and also not a username... 
    // Nothing else to do at this point but show a 404 
    show_404($segments[0]); 

} 

}

2

這是你以後:

$route['(:any)/(:any)'] = '$2/$1'; 

在您的所有功能定義具有用戶名作爲最後一個參數:

class Controller{function page(var1, var2, ..., varn, username){}} 

或者,如果你只是想在一個具體的頁面上你可以這樣做:

$route['(:any)/controller/page/(:any)'] = 'controller/page/$2/$1'; //This will work for the above class. 

或者,如果你想要它的一些功能我N A控制器,你可以這樣做:

$route['(:any)/controller/([func1|func2|funcn]+)/(:any)'] = 'controller/$2/$3/$1'; 
+0

這是對使用路由器類很好的解釋,但它不完全我在找什麼,因爲爲所有控制器中的所有方法添加額外的輸入參數會很麻煩。 – ainla

相關問題