Hex 发表于 2013-4-10 17:33:05

CodeIgniter 源码分析之 URI.php

原文: http://blog.163.com/wu_guoqing/blog/static/19653701820128167448426/
作者: Calix

<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------

/**
* URI Class
*/
class CI_URI {

/**
* List of cached uri segments
*/
var $keyval   = array();

/**
* Current uri string
*/
var $uri_string;

/**
* List of uri segments
*/
var $segments= array();

/**
* Re-indexed list of uri segments
*/
var $rsegments= array();

/**
* Constructor
*/
function __construct()
{
$this->config =& load_class('Config', 'core');
log_message('debug', "URI Class Initialized");
}


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

/**
* Get the URI String
*/
//URI组件里面有很多方法,大都是一些辅助作用的方法,而此方法是URI最主线的一个方法。
function _fetch_uri_string()
{
//下面的uri_protocol是在config.php里面的一个配置项,其实是问你用哪种方式去检测uri的信息的意思,
//默认是AUTO,自动检测,也就是通过各种方式检测,直至检测到,或者全部方式都检测完。。
if (strtoupper($this->config->item('uri_protocol')) == 'AUTO')
{
   //开始尝试各种方式,主要有:命令行,REQUEST_URI, PATH_INFO, QUERY_STRING.
   
   //下面会多次出现$this->_set_uri_string($str)这个方法,这个方法没别的,就是把$str经过
   //过滤和修剪后值给$this->uri_string属性,在这里暂时可以理解为就是赋值。
   
   //如果脚本是在命令行模式下运行的话,那么参数就是通过$_SERVER['argv']来传递。下面的
   //$this->_parse_cli_args();就是拿到符合我们需要的路由相关的一些参数鸟~如果大部分
   //情况你没用命令行执行脚本的话,下面这个if暂时可以不用管。
   if (php_sapi_name() == 'cli' or defined('STDIN'))
   {
    $this->_set_uri_string($this->_parse_cli_args());
    return;
   }

   //这种REQUEST_URI方式相对复杂一点,因此封装在$this->_detect_uri();里面。
   //其实大多数情况下,利用REQUEST URI和SCRIPT NAME都会得到我们想要的路径信息了。
   if ($uri = $this->_detect_uri())
   {
    $this->_set_uri_string($uri);
    return;
   }

   //PATH_INFO方式,个人觉得这种方式最经济,只是不是每次请求都有$_SERVER['PATH_INFO']这个变量。
   $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
   if (trim($path, '/') != '' && $path != "/".SELF)
   {
    $this->_set_uri_string($path);
    return;
   }

   //如果是用QUERY_STRING的话,路径格式一般为index.php?/controller/method/xxx/xxx
   $path =(isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
   if (trim($path, '/') != '')
   {
    $this->_set_uri_string($path);
    return;
   }

   //上面的方法都不行,那真是奇怪了。。所以尝试最后一种奇葩的方法,就是从$_GET里面把那个键名拿出来。
   if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')
   {
    $this->_set_uri_string(key($_GET));
    return;
   }

   // We've exhausted all our options...
   $this->uri_string = '';
   return;
}

//厄,这里是因为上面那个获得uri_protocol配置的语句写在if里面,然后又没赋值到某个变量,所以这里要再写一次了
//可能是因为大多数情况下,我们都是选择AUTO方式吧。但是,这样写又何必呢。。
$uri = strtoupper($this->config->item('uri_protocol'));

//其实就是按规定的方式去找路径而已。。
if ($uri == 'REQUEST_URI')
{
   $this->_set_uri_string($this->_detect_uri());
   return;
}
elseif ($uri == 'CLI')
{
   $this->_set_uri_string($this->_parse_cli_args());
   return;
}

//如果你在配置文件config.php里面把这个uri_protocol定义成一种上面都没有的方式,那么就会执行下面的代码。
//意思是,就看$_SERVER有没有这个uri_protocol的变量了,有就给,没有就拉倒。
$path = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
$this->_set_uri_string($path);
}

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

/**
* Set the URI String
*/
function _set_uri_string($str)
{
// Filter out control characters
$str = remove_invisible_characters($str, FALSE);

// If the URI contains only a slash we'll kill it
$this->uri_string = ($str == '/') ? '' : $str;
}

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

/**
* Detects the URI
*/
private function _detect_uri()
{
//如果这两个值缺少其中一个,那么这种方法行不通。
if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME']))
{
   return '';
}

$uri = $_SERVER['REQUEST_URI'];//取得request_uri

//注意下面这个是===0不是false!接下来这个if 和下面的elseif分别是script_name有文件名和没有文件名(如
//http://abc.com/CI/或者http://abc.com/CI/?c=index&m=welcome等)的不同情况的处理。
if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
{
   //去掉共同部分,取得对路由有用的部分。   
   $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
}
elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
{
   //作用同上
   $uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
}

//这里是为兼容?/abc/xx/的形式。
if (strncmp($uri, '?/', 2) === 0)
{
   $uri = substr($uri, 2);
}

//在这里$uri可能是?xxx=xx的形式,也可能是直接xxx=xx,也可能是/
$parts = preg_split('#\?#i', $uri, 2);
$uri = $parts;
//如果是能通过上述的正则分割出两段,那么,是通过query_string即?的形式进行路由访问
if (isset($parts))
{
   $_SERVER['QUERY_STRING'] = $parts;
   parse_str($_SERVER['QUERY_STRING'], $_GET);
}
else
{
   $_SERVER['QUERY_STRING'] = '';
   $_GET = array();
}

//如果为/,或者为空,有两种情况,要么就是通过query_string,所以此时$parts就是等于下面两种可能,同时我们
//已经通过$parts拿到要拿的信息,则可以返回。要么就是以段的形式,但是段的信息为空,即直接访问入口文件而没有
//任何路由信息的传递,也可以直接返回。
if ($uri == '/' || empty($uri))
{
   return '/';
}

//这里我个人觉得是上面的strpos($uri, $_SERVER['SCRIPT_NAME']) === 0和elseif都无法匹配的时候,
//返回这个url的path部分。
$uri = parse_url($uri, PHP_URL_PATH);

// Do some final cleaning of the URI and return it
return str_replace(array('//', '../'), '/', trim($uri, '/'));
}

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

/**
* Parse cli arguments
*/
private function _parse_cli_args()
{
//返回在命令行模式下运行时传递的参数。
$args = array_slice($_SERVER['argv'], 1);//因为第一个参数是当前文件名,所以从第二个开始才是我们要获取的。

//返回一个由'/'字符串拼接的字符串,因为$this->uri_string是一个字符串。
return $args ? '/' . implode('/', $args) : '';
}

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

/**
* Filter segments for malicious characters
*/
//过滤不合法字符
function _filter_uri($str)
{
if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE)
{
   // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
   // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
   if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str))
   {
    show_error('The URI you submitted has disallowed characters.', 400);
   }
}

// Convert programatic characters to entities
$bad = array('$','(',')','%28','%29');
$good = array('&#36;', '&#40;', '&#41;', '&#40;', '&#41;');

return str_replace($bad, $good, $str);
}

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

/**
* Remove the suffix from the URL if needed
*/
//去掉url的我们自定义的后缀。
function _remove_url_suffix()
{

if($this->config->item('url_suffix') != "")
{
   $this->uri_string = preg_replace("|".preg_quote($this->config->item('url_suffix'))."$|", "", $this->uri_string);
}
}

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

/**
* Explode the URI Segments. The individual segments will
* be stored in the $this->segments array.
*/
//把uri_string拆成段(同时对各段进行过滤),保存到URI::$segments中。
function _explode_segments()
{
foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
{
   // Filter segments for security
   $val = trim($this->_filter_uri($val));

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

// --------------------------------------------------------------------
/**
* Re-index Segments
*/
//使得出来的段以下标1开始保存。
function _reindex_segments()
{
array_unshift($this->segments, NULL);
array_unshift($this->rsegments, NULL);
unset($this->segments);
unset($this->rsegments);
}

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

/**
* Fetch a URI Segment
*/
//返回某一段
function segment($n, $no_result = FALSE)
{
return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n];
}

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

/**
* Fetch a URI "routed" Segment
*/
//返回确定路由后的某一段
function rsegment($n, $no_result = FALSE)
{
return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n];
}

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

/**
* Generate a key value pair from the URI string
*/
function uri_to_assoc($n = 3, $default = array())
{
return $this->_uri_to_assoc($n, $default, 'segment');
}
/**
* Identical to above only it uses the re-routed segment array
*/
function ruri_to_assoc($n = 3, $default = array())
{
return $this->_uri_to_assoc($n, $default, 'rsegment');
}

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

/**
* Generate a key value pair from the URI string or Re-routed URI string
*/
function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
{
if ($which == 'segment')
{
   $total_segments = 'total_segments';
   $segment_array = 'segment_array';
}
else
{
   $total_segments = 'total_rsegments';
   $segment_array = 'rsegment_array';
}

if ( ! is_numeric($n))
{
   return $default;
}

if (isset($this->keyval[$n]))
{
   return $this->keyval[$n];
}

if ($this->$total_segments() < $n)
{
   if (count($default) == 0)
   {
    return array();
   }

   $retval = array();
   foreach ($default as $val)
   {
    $retval[$val] = FALSE;
   }
   return $retval;
}

$segments = array_slice($this->$segment_array(), ($n - 1));

$i = 0;
$lastval = '';
$retval= array();
foreach ($segments as $seg)
{
   if ($i % 2)
   {
    $retval[$lastval] = $seg;
   }
   else
   {
    $retval[$seg] = FALSE;
    $lastval = $seg;
   }

   $i++;
}

if (count($default) > 0)
{
   foreach ($default as $val)
   {
    if ( ! array_key_exists($val, $retval))
    {
   $retval[$val] = FALSE;
    }
   }
}

// Cache the array for reuse
$this->keyval[$n] = $retval;
return $retval;
}

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

/**
* Generate a URI string from an associative array
*/
function assoc_to_uri($array)
{
$temp = array();
foreach ((array)$array as $key => $val)
{
   $temp[] = $key;
   $temp[] = $val;
}

return implode('/', $temp);
}

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

/**
* Fetch a URI Segment and add a trailing slash
*/
function slash_segment($n, $where = 'trailing')
{
return $this->_slash_segment($n, $where, 'segment');
}

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

/**
* Fetch a URI Segment and add a trailing slash
*/
function slash_rsegment($n, $where = 'trailing')
{
return $this->_slash_segment($n, $where, 'rsegment');
}

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

/**
* Fetch a URI Segment and add a trailing slash - helper function
*/
function _slash_segment($n, $where = 'trailing', $which = 'segment')
{
$leading = '/';
$trailing = '/';

if ($where == 'trailing')
{
   $leading = '';
}
elseif ($where == 'leading')
{
   $trailing = '';
}

return $leading.$this->$which($n).$trailing;
}

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

/**
* Segment Array
*/
function segment_array()
{
return $this->segments;
}

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

/**
* Routed Segment Array
*/
function rsegment_array()
{
return $this->rsegments;
}

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

/**
* Total number of segments
*/
function total_segments()
{
return count($this->segments);
}

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

/**
* Total number of routed segments
*/
function total_rsegments()
{
return count($this->rsegments);
}

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

/**
* Fetch the entire URI string
*/
function uri_string()
{
return $this->uri_string;
}


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

/**
* Fetch the entire Re-routed URI string
*/
function ruri_string()
{
return '/'.implode('/', $this->rsegment_array());
}

}
页: [1]
查看完整版本: CodeIgniter 源码分析之 URI.php