CI框架源码解读--ROUTE和URL类

2016年8月10日23:17

路由的目的是为了从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], " \t\n\r\0\x0B/") : '';

            if ($_d !== '')
            {
                $this->uri->filter_uri($_d);
                $this->set_directory($_d);
            }
        }

        $_c = trim($this->config->item('controller_trigger'));
        if ( ! empty($_GET[$_c]))
        {
            $this->uri->filter_uri($_GET[$_c]);
            $this->set_class($_GET[$_c]);

            $_f = trim($this->config->item('function_trigger'));
            if ( ! empty($_GET[$_f]))
            {
                $this->uri->filter_uri($_GET[$_f]);
                $this->set_method($_GET[$_f]);
            }

            $this->uri->rsegments = array(
                1 => $this->class,
                2 => $this->method
            );
        }
        else
        {
            $this->_set_default_controller();
        }

        // Routing rules don't apply to query strings and we don't need to detect
        // directories, so we're done here
        return;
    }

    // Is there anything to parse?
    //这里的$this->uri是route类构造函数里面$this->uri =& load_class('URI', 'core');来的,后文我们会详细看URI类
    if ($this->uri->uri_string !== '')
    {
        //绝大多数情况是会走这里
        $this->_parse_routes();
    }
    else
    {
        $this->_set_default_controller();
    }

所以我们重点再看ROUTE的_parse_routes()方法:

/**
 * Parse Routes
 *
 * 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.
 *
 * @return  void
 */
protected function _parse_routes()
{
    // Turn the segment array into a URI string
    // $this->uri->segments我们后面也会讲到
    $uri = implode('/', $this->uri->segments);

    // Get HTTP verb
    $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli';

    // Loop through the route array looking for wildcards
    // 查看是否符合config文件里的配置
    foreach ($this->routes as $key => $val)
    {
        // Check if route format is using HTTP verbs
        if (is_array($val))
        {
            $val = array_change_key_case($val, CASE_LOWER);
            if (isset($val[$http_verb]))
            {
                $val = $val[$http_verb];
            }
            else
            {
                continue;
            }
        }

        // Convert wildcards to RegEx
        $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);

        // Does the RegEx match?
        if (preg_match('#^'.$key.'$#', $uri, $matches))
        {
            // Are we using callbacks to process back-references?
            if ( ! is_string($val) && is_callable($val))
            {
                // Remove the original string from the matches array.
                array_shift($matches);

                // Execute the callback using the values in matches as its parameters.
                $val = call_user_func_array($val, $matches);
            }
            // Are we using the default routing method for back-references?
            elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE)
            {
                $val = preg_replace('#^'.$key.'$#', $val, $uri);
            }

            $this->_set_request(explode('/', $val));
            return;
        }
    }

    // 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(array_values($this->uri->segments));
}

再看_set_request()方法:

/**
 * Set request route
 *
 * Takes an array of URI segments as input and sets the class/method
 * to be called.
 *
 * @used-by CI_Router::_parse_routes()
 * @param   array   $segments   URI segments
 * @return  void
 */
protected function _set_request($segments = array())
{
    $segments = $this->_validate_request($segments);
    // If we don't have any segments left - try the default controller;
    // WARNING: Directories get shifted out of the segments array!
    if (empty($segments))
    {
        $this->_set_default_controller();
        return;
    }

    if ($this->translate_uri_dashes === TRUE)
    {
        $segments[0] = str_replace('-', '_', $segments[0]);
        if (isset($segments[1]))
        {
            $segments[1] = str_replace('-', '_', $segments[1]);
        }
    }

    //找到类名了
    $this->set_class($segments[0]);
    if (isset($segments[1]))
    {
        //找到方法名了
        $this->set_method($segments[1]);
    }
    else
    {
        $segments[1] = 'index';
    }

    array_unshift($segments, NULL);
    unset($segments[0]);
    $this->uri->rsegments = $segments;

到这里,就根据URL找出了类名和方法名,在引导文件system/core/CodeIgniter.php里面就可以实现调度了。

$class = ucfirst($RTR->class);
$method = $RTR->method;

$CI = new $class();

/*
 * ------------------------------------------------------
 *  Call the requested method
 * ------------------------------------------------------
 */
call_user_func_array(array(&$CI, $method), $params);

下面我们看下URI类,来看看上面代码里的$this->uri等各项是怎么得到的。

在URI类的构造函数里有一步:

$this->_set_uri_string($uri)

_set_uri_string()方法代码如下:

/**
 * Set URI String
 *
 * @param   string  $str
 * @return  void
 */
protected function _set_uri_string($str)
{
    // Filter out control characters and trim slashes
    $this->uri_string = trim(remove_invisible_characters($str, FALSE), '/');

    if ($this->uri_string !== '')
    {
        // Remove the URL suffix, if present
        if (($suffix = (string) $this->config->item('url_suffix')) !== '')
        {
            $slen = strlen($suffix);

            if (substr($this->uri_string, -$slen) === $suffix)
            {
                $this->uri_string = substr($this->uri_string, 0, -$slen);
            }
        }

        $this->segments[0] = NULL;
        // Populate the segments array
        foreach (explode('/', trim($this->uri_string, '/')) as $val)
        {
            $val = trim($val);
            // Filter segments for security
            $this->filter_uri($val);

            if ($val !== '')
            {
                $this->segments[] = $val;
            }
        }

        unset($this->segments[0]);
    }
}

如果你的原始uri是http://example.com/index.php/news/local/metro/crime_is_up的话,经过这个_set_uri_string()方法处理,你会得到$this->segments = array([1]=>'news', [2]=>'local',[3]=>'metro',[4]=>'crime_is_up')

参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容