/system/core/Router.php 路由器类

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

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

/**
 * Router Class
 * 路由器类
 * 
 * Parses URIs and determines routing
 * 解析URI和确定路由
 * 
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @author		ExpressionEngine Dev Team
 * @category	Libraries
 * @link		http://codeigniter.com/user_guide/general/routing.html
 */
class CI_Router {

	/**
	 * Config class
	 * 配置类
	 * @var object
	 * @access public
	 */
	var $config;
	
	
	/**
	 * List of routes
	 * 路由列表
	 * @var array
	 * @access public
	 */
	var $routes			= array();
	
	
	/**
	 * List of error routes
	 * 错误路线一览
	 * @var array
	 * @access public
	 */
	var $error_routes	= array();
	
	
	/**
	 * Current class name
	 * 当前的类名
	 * @var string
	 * @access public
	 */
	var $class			= '';
	
	
	/**
	 * Current method name
	 * 目前的方法名
	 * @var string
	 * @access public
	 */
	var $method			= 'index';
	
	
	/**
	 * Sub-directory that contains the requested controller class
	 * 包含所请求的控制器类的子目录
	 * @var string
	 * @access public
	 */
	var $directory		= '';
	
	
	/**
	 * Default controller (and method if specific)
	 * 默认控制器(和具体的方法,如果)
	 * @var string
	 * @access public
	 */
	var $default_controller;

	
	/**
	 * Constructor
	 *
	 * Runs the route mapping function.
	 * 运行路由映射功能。
	 */
	function __construct()
	{
		//配置类
		$this->config =& load_class('Config', 'core');
		//解析uri类
		$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.
	 * 此功能决定什么应该送达的URI请求的基础上,以及任何路由配置文件中已经设置的“航线”。
	 * @access	private
	 * @return	void
	 */
	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
		// 查询字符串在配置文件中启用?通常情况下,CI不使用查询字符串
		// 因为URI段更多的搜索引擎友好的,但他们可以有选择地使用。
		// 如果启用了此功能,我们将收集目录/类/方法有点不同
		$segments = array();
		//enable_query_strings如果设置了查询字符串
		//并且 在_GET中已经存在了默认需要的查询字符串控件器类的关键字时
		//进行查询字符串处理
		if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')]))
		{
			//如果在GET中也有 directory_trigger的话
			if (isset($_GET[$this->config->item('directory_trigger')]))
			{
				//将GET中的directory_trigger进行uri恶意字符串过滤一下
				//然后设置为目录名称
				$this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')])));
				$segments[] = $this->fetch_directory(); //放入到segmetns数组中去
			}

			//如果只有控件器存在的话
			if (isset($_GET[$this->config->item('controller_trigger')]))
			{
				//设置class
				$this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')])));
				$segments[] = $this->fetch_class(); //将class放入到$segments数组中去
			}

			//如果方法名存在
			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(); //放入到$segments数组中去
			}
		}

		// Load the routes.php file. //加载项目的路由配置文件
		if (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');
		}

		//判断自定义路由是否存在
		$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.
		// 不相关的URI到一个有效的控制器。
	    //设置默认控制器,如果为不存或者为空,直接设置为空值
		$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.
		// 有任何查询字符串段?如果是这样的话,我们会验证他们摆脱困境,因为我们就大功告成了。
		if (count($segments) > 0)
		{
			return $this->_validate_request($segments);
		}

		// Fetch the complete URI string
		// 取完整的URI字符串
		$this->uri->_fetch_uri_string();

		// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
		// 是否有一个URI字符串?如果不是这样,“航线”文件中指定默认的控制器将被显示。
		if ($this->uri->uri_string == '')
		{
			return $this->_set_default_controller();
		}

		// Do we need to remove the URL suffix?
		$this->uri->_remove_url_suffix();

		// Compile the segments into an array
		$this->uri->_explode_segments();

		// Parse any custom routing that may exist
		$this->_parse_routes();

		// Re-index the segment array so that it starts with 1 rather than 0
		$this->uri->_reindex_segments();
	}

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

	/**
	 * Set the default controller
	 * 设置默认控制器
	 * @access	private
	 * @return	void
	 */
	function _set_default_controller()
	{
		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?
		//方法被指定?
		if (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开始,而不是0
		$this->uri->_reindex_segments();

		log_message('debug', "No URI present. Default controller set.目前没有URI。默认控制器集");
	}

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

	/**
	 * Set the Route
	 * 设置路由
	 * 
	 * This function takes an array of URI segments as
	 * input, and sets the current class/method
	 * 此功能需要一个数组URI段输入,并设置当前的类/方法
	 * 
	 * @access	private
	 * @param	array
	 * @param	bool
	 * @return	void
	 */
	function _set_request($segments = array())
	{
		$segments = $this->_validate_request($segments);

		//如果为空,直接设置默认的路由器
		if (count($segments) == 0)
		{
			return $this->_set_default_controller();
		}
		
        //设置类
		$this->set_class($segments[0]);

		if (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->rsegments = $segments;
	}

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

	/**
	 * 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?
		// 在项目中查找该控制器,因为$segments[0]保存的是控制器的名称
		//如果该文件存在,直接返回
		if (file_exists(APPPATH.'controllers/'.$segments[0].'.php'))
		{
			return $segments; 
		}

		// Is the controller in a sub-folder?
		// 是一个子文件夹中的控制器吗?
		//如果是一个目录 
		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); //并将目录从$segments数组中去掉

			//
			if (count($segments) > 0)
			{
				// Does the requested controller exist in the sub-folder?
				// 请求的控制器是否存在子文件夹中?
				//判断控件器是否存在指定的目录 中
				//如果不存
				if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php'))
				{
					//判断路由中覆盖404的如果不为空时
					if ( ! empty($this->routes['404_override']))
					{
						//分割为数组
						$x = explode('/', $this->routes['404_override']);

						//设置目录为空
						$this->set_directory('');
						$this->set_class($x[0]); //设置class为第一个参数
						//设置方法
						$this->set_method(isset($x[1]) ? $x[1] : 'index');
                        //直接返回
						return $x;
					}
					else
					{
						//否则直接显示系统的404错误提示
						show_404($this->fetch_directory().$segments[0]);
					}
				}
			}
			else
			{
				// Is the method being specified in the route?
				// 路由中指定的方法吗?
				// 如果路由中有/字符串
				if (strpos($this->default_controller, '/') !== FALSE)
				{
					//进行字符串分割
					$x = explode('/', $this->default_controller);

					$this->set_class($x[0]);  //设置class
					$this->set_method($x[1]); //设置method
				}
				else
				{
					//如果没有,设置class
					$this->set_class($this->default_controller);
					$this->set_method('index'); 
					//设置method
				}

				// Does the default controller exist in the sub-folder?
				//默认的控制器是否存在子文件夹中?
				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
		// 如果我们找到了这一步,这意味着那个URI并没有一个有效的相关
		// 控制器类。现在,我们将看到,如果有一个手柄
		
		//同上面的一样,当控件器不存在的时候片时
		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.
	 * 此功能匹配任何路由中可能存在的config/ routes.php下文件针对的URI。
	 * 类/方法确定是否需要重新映射。
	 *
	 * @access	private
	 * @return	void
	 */
	function _parse_routes()
	{
		// Turn the segment array into a URI string
		// 关闭段到URI字符串数组
		//将uri->segments拼接成字符串
		$uri = implode('/', $this->uri->segments);

		
		// Is there a literal match?  If so we're done
		// 是否有文字匹配?如果是这样,我们就大功告成了
		//判断在routes中是否有配置的路由设置
		if (isset($this->routes[$uri]))
		{
			//如果有,直接设置路由了
			return $this->_set_request(explode('/', $this->routes[$uri]));
		}

		// Loop through the route array looking for wild-cards
		// 循环通过路由阵列寻找野生卡
		//循环路由设置
		foreach ($this->routes as $key => $val)
		{
			// Convert wild-cards to RegEx
			// 正则表达式转换通配符
			$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

			// Does the RegEx match?
			// 正则表达式匹配吗?
			if (preg_match('#^'.$key.'$#', $uri))
			{
				// Do we have a back-reference?
				// 我们有一个回参考?
				if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
				{
					$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
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_class($class)
	{
		$this->class = str_replace(array('/', '.'), '', $class);
	}

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

	/**
	 * Fetch the current class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_class()
	{
		return $this->class;
	}

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

	/**
	 *  Set the method name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_method($method)
	{
		$this->method = $method;
	}

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

	/**
	 *  Fetch the current method
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_method()
	{
		if ($this->method == $this->fetch_class())
		{
			return 'index';
		}

		return $this->method;
	}

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

	/**
	 *  Set the directory name
	 *  设置的目录名
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_directory($dir)
	{
		$this->directory = str_replace(array('/', '.'), '', $dir).'/';
	}

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

	/**
	 *  Fetch the sub-directory (if any) that contains the requested controller class
	 *
	 * @access	public
	 * @return	string
	 */
	function fetch_directory()
	{
		return $this->directory;
	}

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

	/**
	 *  Set the controller overrides
	 *  设置控制器覆盖
	 *  
	 * @access	public
	 * @param	array
	 * @return	null
	 */
	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 */

  

posted @ 2013-05-12 00:27  简单--生活  阅读(672)  评论(0)    收藏  举报
简单--生活(CSDN)