CI架構源碼翻閱-Router.php

來源:互聯網
上載者:User
CI架構源碼閱讀---------Router.php
config =& load_class('Config', 'core');$this->uri =& load_class('URI', 'core');log_message('debug', "Router Class Initialized");}// --------------------------------/** * Set the route mapping * * This function determines 確定,決心 what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * 設定預設的路由資訊,如果不存在控制器資訊,則根據routes.php的設定來載入預設的控制器, * * @accessprivate * @returnvoid */function _set_routing(){// Are query strings enabled in the config file?  Normally CI doesn't utilize 運用 query strings// since URI segments are more search-engine friendly, but they can optionally 視情況 be used.// If this feature is enabled, we will gather  the directory/class/method a little differently// 如果項目是允許通過query_strings的形式,並且有通過$_GET的方式請求控制器的話,則以query_string形式路由// 上面這裡為什麼還要判斷有沒有通過get的方式指定控制器?// 其實是因為如果允許query_string的形式請求路由,但是卻沒有在APPPATH/config/config.php下配置 // controller_trigger,function_trigger,directory_trigger這三項的話,也是不能使用query_strings形式的// 此時,我們依然會採用“段”的形式。$segments = array();if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])){//取得目錄名,控制名和方法名傳遞的變數名。這三項都是在config/config.php裡面定義的。if (isset($_GET[$this->config->item('directory_trigger')])){$this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')])));$segments[] = $this->fetch_directory();}if (isset($_GET[$this->config->item('controller_trigger')])){$this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')])));$segments[] = $this->fetch_class();}if (isset($_GET[$this->config->item('function_trigger')])){$this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')])));$segments[] = $this->fetch_method();}}// Load the routes.php file.// 根據當前環境載入APPPATH下面的routes.phpif (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php')){include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');}elseif (is_file(APPPATH.'config/routes.php')){include(APPPATH.'config/routes.php');}// 下面的這個$route變數是在routes.php中定義的用來設定預設的控制器和預設的404頁面$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;unset($route);// 利用完就幹掉,過河拆橋,毫不留情。// Set the default controller so we can display it in the event事件// the URI doesn't correlated 相關的 to a valid 有效 controller.// 根據剛才的配置資訊,設定預設控制器,沒有的話,就為FLASE。$this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']);// Were there any query string segments?  If so, we'll validate them and bail out since we're done.// 驗證有沒有通過query string的方式拿到目錄名,控制名和方法名其中的任何一個。// 如果拿到了就直接確定路由返回if (count($segments) > 0){// 確定並設定路由。return $this->_validate_request($segments);}// Fetch the complete URI string// 這個函數的作用是從uri中檢測處理,把我們確定路由需要的資訊(例如index.php/index/welcome/1後// 面index/welcome/1這串)放到$this->uri->uri_string中。$this->uri->_fetch_uri_string();// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.// 如果uri_string為空白的話,那麼就用把路由設定為預設的。/*if ($this->uri->uri_string == ''){return $this->_set_default_controller();}*/// Do we need to remove the URL suffix?// 去掉URI尾碼,因為CI允許在uri後面加尾碼,但它其實對我們尋找路由是多餘,而且會造成影響的,所以先去掉。$this->uri->_remove_url_suffix();// Compile 編譯 the segments into an array// 將uri拆分正段同時對每個段進行過濾,並存入$this->segments[]中$this->uri->_explode_segments();// Parse any custom routing that may exist// 處理路由,根據路由設定APPPATH/config/routes.php來$this->_parse_routes();// Re-index the segment array so that it starts with 1 rather than 0// 將uri段索引設定為從1開始$this->uri->_reindex_segments();}// --------------------------------/** * Set the default controller * 設定預設的控制器 * @accessprivate * @returnvoid */function _set_default_controller(){// 在Router::_set_routing()函數中從設定檔裡面讀取預設控制器名,如果沒有就有FALSE// 本檔案的158行if ($this->default_controller === FALSE){show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file.");}// Is the method being specified?// 通過判斷$this->default_controller有沒有/來確定是否有指定的方法// 如果沒有設定為預設方法indexif (strpos($this->default_controller, '/') !== FALSE){$x = explode('/', $this->default_controller);$this->set_class($x[0]);$this->set_method($x[1]);$this->_set_request($x);}else{$this->set_class($this->default_controller);$this->set_method('index');$this->_set_request(array($this->default_controller, 'index'));}// re-index the routed segments array so it starts with 1 rather than 0// 重新索引段,使得出來的段以下標1開始儲存。 $this->uri->_reindex_segments();log_message('debug', "No URI present. Default controller set.");}// --------------------------------/** * Set the Route * 設定路由 * This function takes 取走,預備動作 an array of URI segments as * input, and sets the current class/method * * @accessprivate * @paramarray * @parambool * @returnvoid */function _set_request($segments = array()){// Router::_validate_request()的作用是檢測尋找出一個正確存在的路由,並確定它$segments = $this->_validate_request($segments);//  這個函數是由_set_default_controller總調用的看216-230行會發現這個$segments 是肯定不會為空白的//  那麼下面這兩句可能是為了防止本方法在其他的地方調用當參數為空白的時候調用_set_default_controller()//  再調用回來$segments就不會為空白了,因為當$segments為空白的時候是不可能進行設定路由的。if (count($segments) == 0){return $this->_set_default_controller();}// 設定類名也就是目錄名$this->set_class($segments[0]);// 如果方法名存在則設定如果不存在則設定為indexif (isset($segments[1])){// A standard method request$this->set_method($segments[1]);}else{// This lets the "routed" segment array identify that the default// index method is being used.$segments[1] = 'index';}// Update our "routed" segment array to contain the segments.// Note: If there is no custom routing, this array will be// identical to $this->uri->segments// 更新路由的段數組,這裡如果沒有自訂的路由那麼將和$this->uri->segments是一樣的$this->uri->rsegments = $segments;}// --------------------------------/** * Validates 使有效 the supplied segments.  Attempts 企圖 to determine 決定 the path to * the controller. * 使提供的段有效並企圖決定控制器的路徑 * @accessprivate * @paramarray * @returnarray */function _validate_request($segments){// ??????????????if (count($segments) == 0){return $segments;}// Does the requested controller exist in the root folder?// 確定存在$segments[0]是否存在於APPPATH/controllers/檔案夾下的php檔案if (file_exists(APPPATH.'controllers/'.$segments[0].'.php')){return $segments;}// Is the controller in a sub-folder?// $segments[0]是否為APPPATH/controllers下的子目錄if (is_dir(APPPATH.'controllers/'.$segments[0])){// Set the directory and remove it from the segment array// 如果的確是目錄,那麼就可以確定路由的目錄部分了。 設定目錄$this->set_directory($segments[0]);// 去掉目錄部分。進一步進行路由尋找。$segments = array_slice($segments, 1);// 如果uri請求中除了目錄還有其它段,那說明是有請求某指定控制器的。if (count($segments) > 0){// Does the requested controller exist in the sub-folder?// 判斷請求的$segments[0]是不是在於APPPATH/controllers/的子目錄中php檔案if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php')){// 報錯也有兩方式,一種是預設的,一種是自義定的。// 下面這個404_override就是在config/routes.php定義的一個路由找不// 到時候的預設處理控制器了,如果有定義我們調用它。if ( ! empty($this->routes['404_override'])){$x = explode('/', $this->routes['404_override']);// 把剛才設定好的路由的目錄部分去掉,因為現在路由是我們定義的404路由。$this->set_directory('');// 這裡可以看出,我們定義的404路由是不允許放在某個目錄下的,只能直接放在controllers/下$this->set_class($x[0]);$this->set_method(isset($x[1]) ? $x[1] : 'index');return $x;}else{// 預設404報錯show_404($this->fetch_directory().$segments[0]);}}}else{// 如果uri請求中只有目錄我們才會來到這// Is the method being specified 指定的 in the route?// 下面這個判斷只是判斷一下$this->default_controller有沒有指定方法而已。if (strpos($this->default_controller, '/') !== FALSE){$x = explode('/', $this->default_controller);$this->set_class($x[0]);$this->set_method($x[1]);}else{$this->set_class($this->default_controller);$this->set_method('index');}// Does the default controller exist in the sub-folder?// 判斷APPPATH/controllers/目錄/下面是否存在預設的方法if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')){$this->directory = '';return array();}}return $segments;}// If we've gotten 達到 this far 遙遠的 it means that the URI does not correlate 使相關聯 to a valid// controller class.  We will now see if there is an override// 來到這裡,就說明了,即找不到controllers/下相應的控制器,也找不到這樣的目錄。那就報錯咯。if ( ! empty($this->routes['404_override'])){$x = explode('/', $this->routes['404_override']);$this->set_class($x[0]);$this->set_method(isset($x[1]) ? $x[1] : 'index');return $x;}// Nothing else to do at this point but show a 404// 展示一個404頁面show_404($segments[0]);}// --------------------------------/** *  Parse Routes *  解析路由 * This function matches 匹配 any routes that may exist in * the config/routes.php file against 針對,反對 the URI to * determine 決定,決心 if the class/method need to be remapped.重新繪製地圖 * * @accessprivate * @returnvoid */function _parse_routes(){// Turn the segment array into a URI string// 將segments數組轉為uri字串的形式$uri = implode('/', $this->uri->segments);// Is there a literal 文字的,字面的 match?  If so we're done// 如果這個uri是routes.php中定義的那麼。。。。。if (isset($this->routes[$uri])){return $this->_set_request(explode('/', $this->routes[$uri]));}// Loop through the route array looking for wild-cardsforeach ($this->routes as $key => $val){// Convert wild-cards to RegEx 使用萬用字元進行正則轉換// 如果$key 中含有:any 轉換為.+  , :num 轉換為 [0-9]+$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));// Does the RegEx match? 進行正則匹配// 從這裡可以看出如果routes.php 中的$route的key是可以使用:any 或者 :num// 來進行匹配的。舉個例子來說// routes.php 中有 $route['show:any:num'] = 'anynum'; // 這樣的兩個配置那麼我們就可以將showaa123這樣的uri匹配到了它對應的值就是anynumif (preg_match('#^'.$key.'$#', $uri)){// Do we have a back-reference?如果$val中有$並且$key中有(// 這個if的作用我沒看懂。。。待高人解救// 有明白的請發郵箱uuus007@gmail.comif (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE){// 將uri中能匹配到得字元替換成$val$val = preg_replace('#^'.$key.'$#', $val, $uri);}return $this->_set_request(explode('/', $val));}}// If we got this far it means we didn't encounter a// matching route so we'll set the site default route// 如果我們走到這一步,這意味著我們沒有遇到一個匹配的路由// 所以我們將設定網站預設路由$this->_set_request($this->uri->segments);}// --------------------------------/** * Set the class name * * @accesspublic * @paramstring * @returnvoid */function set_class($class){$this->class = str_replace(array('/', '.'), '', $class);}// --------------------------------/** * Fetch the current class * * @accesspublic * @returnstring */function fetch_class(){return $this->class;}// --------------------------------/** *  Set the method name * * @accesspublic * @paramstring * @returnvoid */function set_method($method){$this->method = $method;}// --------------------------------/** *  Fetch the current method * * @accesspublic * @returnstring */function fetch_method(){if ($this->method == $this->fetch_class()){return 'index';}return $this->method;}// --------------------------------/** *  Set the directory name * * @accesspublic * @paramstring * @returnvoid */function set_directory($dir){$this->directory = str_replace(array('/', '.'), '', $dir).'/';}// --------------------------------/** *  Fetch the sub-directory (if any) that contains the requested controller class * * @accesspublic * @returnstring */function fetch_directory(){return $this->directory;}// --------------------------------/** * Set the controller overrides * 控制器覆蓋 * 這個函數可以講目錄,控制器,方法重新覆蓋一遍。 * @accesspublic * @paramarray * @returnnull */function _set_overrides($routing){if ( ! is_array($routing)){return;}if (isset($routing['directory'])){$this->set_directory($routing['directory']);}if (isset($routing['controller']) AND $routing['controller'] != ''){$this->set_class($routing['controller']);}if (isset($routing['function'])){$routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function'];$this->set_method($routing['function']);}}}// END Router Class/* End of file Router.php *//* Location: ./system/core/Router.php */

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.