摘要:支持基于段方法和查詢字符串方法兩種形式的。里的方法就是利用類來實現解析出類名方法名。在類的構造函數里有一步方法代碼如下如果你的原始是的話,經過這個方法處理,你會得到參考文章
路由的目的是為了從URL中解析出class類名是什么,method方法名是什么,所傳的參數有哪些,參數值又是什么,類文件存在的路徑是哪。最終實現方法的調度。
CI支持基于段方法和查詢字符串方法兩種形式的URL。
基于段形式:
example.com/news/article/my_article.html
查詢字符串形式:
index.php?c=products&m=view&id=345
URL的獲取方法有如下幾種:PATH_INFO、QUERY_STRING、REQUEST_URI、ORIG_PATH_INFO。比較常用的是PATH_INFO。幾種方式的差異可以簡單通過打印$_SERVER來查看。比如xxx.com/welcome/test_search.html?c=welcome&d=test_search,打印的結果是(只挑了這幾部分):
Array ( [QUERY_STRING] => c=welcome&d=test_search [REQUEST_URI] => /welcome/test_search.html?c=welcome&d=test_search [PATH_INFO] => /welcome/test_search.html )
下面是源碼config文件里關于這幾種方法的定義。
/* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of "AUTO" works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | "AUTO" Default - auto detects | "PATH_INFO" Uses the PATH_INFO | "QUERY_STRING" Uses the QUERY_STRING | "REQUEST_URI" Uses the REQUEST_URI | "ORIG_PATH_INFO" Uses the ORIG_PATH_INFO | */ $config["uri_protocol"] = "PATH_INFO";
我們這里用的也是PATH_INFO來獲取。
至此,我們就擁有了URL地址,接下來我們就要分析地址。URL類就是來做分析的事情。
system/core/Router.php里的_set_routing()方法就是利用URL類來實現解析出類名方法名。
看下代碼(下面的代碼都是CodeIgniter-3.0.6版本的),英文注釋已經很詳細了,我在關鍵點額外加了點中文注釋:
/** * Set route mapping * * Determines what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * * @return void */ protected function _set_routing() { // Load the routes.php file. It would be great if we could // skip this for enable_query_strings = TRUE, but then // default_controller would be empty ... if (file_exists(APPPATH."config/routes.php")) { include(APPPATH."config/routes.php"); } if (file_exists(APPPATH."config/".ENVIRONMENT."/routes.php")) { include(APPPATH."config/".ENVIRONMENT."/routes.php"); } // Validate & get reserved routes if (isset($route) && is_array($route)) { isset($route["default_controller"]) && $this->default_controller = $route["default_controller"]; isset($route["translate_uri_dashes"]) && $this->translate_uri_dashes = $route["translate_uri_dashes"]; unset($route["default_controller"], $route["translate_uri_dashes"]); $this->routes = $route; } // 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 // 這段不用看,我們項目中是FALSE if ($this->enable_query_strings) { // If the directory is set at this time, it means an override exists, so skip the checks if ( ! isset($this->directory)) { $_d = $this->config->item("directory_trigger"); $_d = isset($_GET[$_d]) ? trim($_GET[$_d], "