codeigniter源代码分析之文件加载类 Loader.php

Loader加载类 做要作用 加载file 加载library 加载helper 加载vars 加载config 加载language

以及加载clas 实例化class 、还有自动加载机制(通过配置文件autoload.php实现)

源代码很长的一个类

<?php
class CI_Loader {

	protected $_ci_ob_level;

	protected $_ci_view_paths		= array();

	protected $_ci_library_paths	= array();

	protected $_ci_model_paths		= array();

	protected $_ci_helper_paths		= array();

	protected $_base_classes		= array(); // Set by the controller class

	protected $_ci_cached_vars		= array();

	protected $_ci_classes			= array();

	protected $_ci_loaded_files		= array();

	protected $_ci_models			= array();

	protected $_ci_helpers			= array();

	protected $_ci_varmap			= array('unit_test' => 'unit',
											'user_agent' => 'agent');

	// 缓存级别、library helper model view 的path
	public function __construct()
	{
		$this->_ci_ob_level  = ob_get_level();
		$this->_ci_library_paths = array(APPPATH, BASEPATH);
		$this->_ci_helper_paths = array(APPPATH, BASEPATH);
		$this->_ci_model_paths = array(APPPATH);
		$this->_ci_view_paths = array(APPPATH.'views/'	=> TRUE);

		log_message('debug', "Loader Class Initialized");
	}
	// 加载实例化的class 加载的文件 加载实例化model 加载实例化的核心类
	public function initialize()
	{
		$this->_ci_classes = array();
		$this->_ci_loaded_files = array();
		$this->_ci_models = array();
		$this->_base_classes =& is_loaded();

		$this->_ci_autoloader();

		return $this;
	}
	// 已经实例化的类不会重复实例化
	public function is_loaded($class)
	{
		if (isset($this->_ci_classes[$class]))
		{
			return $this->_ci_classes[$class];
		}

		return FALSE;
	}
	// 加载library 的类
	public function library($library = '', $params = NULL, $object_name = NULL)
	{
		// 数组
		if (is_array($library))
		{
			foreach ($library as $class)
			{
				$this->library($class, $params);
			}
			return;
		}
		if ($library == '' OR isset($this->_base_classes[$library]))
		{//library名称为空 或者library 跟核心类的名称冲突
			return FALSE;
		}
		if ( ! is_null($params) && ! is_array($params))
		{
			$params = NULL;
		}
		$this->_ci_load_class($library, $params, $object_name);
	}
	public function model($model, $name = '', $db_conn = FALSE)
	{
		if (is_array($model))
		{
			foreach ($model as $babe)
			{
				$this->model($babe);
			}
			return;
		}
		if ($model == '')
		{
			return;//model名为空
		}
		$path = '';
		if (($last_slash = strrpos($model, '/')) !== FALSE)//last_slash 最后出现 '/' 的位置
		{
			$path = substr($model, 0, $last_slash + 1);//路径
			$model = substr($model, $last_slash + 1);//文件名
		}
		if ($name == '')
		{
			$name = $model;//别名为空就不用别名了
		}
		if (in_array($name, $this->_ci_models, TRUE))
		{
			return;//model name已经被加载 停止加载操作
		}
		$CI =& get_instance();
		if (isset($CI->$name))
		{
			// 如果CI类中的属性名称跟现在的model name一样的话 会出现这样的错误报告
			// so model name 注意不要与controller成员属性名称发生冲突
			show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
		}
		// 这里注意 模型文件用小写字母命名 这里将名称全转成小写了
		$model = strtolower($model);
		foreach ($this->_ci_model_paths as $mod_path)//遍历路径
		{
			if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
			{
				continue;// 当前路径中文件不存在
			}

			if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
			{
				if ($db_conn === TRUE)
				{
					$db_conn = '';
				}
				// load DB
				$CI->load->database($db_conn, FALSE, TRUE);
			}
			if ( ! class_exists('CI_Model'))
			{
				load_class('Model', 'core');// 加载CI_Model model基础类
			}
			//加载文件
			require_once($mod_path.'models/'.$path.$model.'.php');
			// 文件里面的类名 首字母大写
			$model = ucfirst($model);
			//实例化 并且赋值给CI的属性
			$CI->$name = new $model();
			$this->_ci_models[] = $name;//加载model 标志
			return;
		}
		show_error('Unable to locate the model you have specified: '.$model);// couldn't find the model
	}
	public function database($params = '', $return = FALSE, $active_record = NULL)
	{
		// Grab the super object
		$CI =& get_instance();

		// Do we even need to load the database class?
		if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db))
		{
			return FALSE;
		}

		require_once(BASEPATH.'database/DB.php');

		if ($return === TRUE)
		{
			return DB($params, $active_record);
		}

		// Initialize the db variable.  Needed to prevent
		// reference errors with some configurations
		$CI->db = '';

		// Load the DB class
		$CI->db =& DB($params, $active_record);
	}
	public function dbutil()
	{
		if ( ! class_exists('CI_DB'))
		{
			$this->database();
		}

		$CI =& get_instance();

		// for backwards compatibility, load dbforge so we can extend dbutils off it
		// this use is deprecated and strongly discouraged
		$CI->load->dbforge();

		require_once(BASEPATH.'database/DB_utility.php');
		require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility.php');
		$class = 'CI_DB_'.$CI->db->dbdriver.'_utility';

		$CI->dbutil = new $class();
	}
	public function dbforge()
	{
		if ( ! class_exists('CI_DB'))
		{
			$this->database();
		}

		$CI =& get_instance();

		require_once(BASEPATH.'database/DB_forge.php');
		require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge.php');
		$class = 'CI_DB_'.$CI->db->dbdriver.'_forge';

		$CI->dbforge = new $class();
	}
	public function view($view, $vars = array(), $return = FALSE)
	{
		return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
	}
	public function file($path, $return = FALSE)
	{
		return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return));
	}
	//添加变量到缓存中 并且这里添加的变量能够被controller的所有function使用(传递到view)
	public function vars($vars = array(), $val = '')
	{
		if ($val != '' AND is_string($vars))
		{
			// vars is key and val is value and 拼接两者成为数组
			$vars = array($vars => $val);
		}
		$vars = $this->_ci_object_to_array($vars);
		if (is_array($vars) AND count($vars) > 0)
		{
			foreach ($vars as $key => $val)
			{
				$this->_ci_cached_vars[$key] = $val; //添加到_ci_cached_vars
			}
		}
	}
	public function get_var($key)
	{
		// return _ci_cached_vars
		return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL;
	}
	public function helper($helpers = array())
	{
		foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper)//遍历helper数组
		{
			if (isset($this->_ci_helpers[$helper]))
			{
				// 已经加载 去其他目录查找
				continue;
			}
			// helper扩展的路径
			$ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php';
			if (file_exists($ext_helper))
			{
				$base_helper = BASEPATH.'helpers/'.$helper.'.php';//基础helper路径
				if ( ! file_exists($base_helper))
				{//基础helper不存在
					show_error('Unable to load the requested file: helpers/'.$helper.'.php');
				}
				//加载基础helper函数跟扩展helper函数
				include_once($ext_helper);
				include_once($base_helper);
				$this->_ci_helpers[$helper] = TRUE;//标志已经加载过
				log_message('debug', 'Helper loaded: '.$helper);
				continue;
			}
			//遍历
			foreach ($this->_ci_helper_paths as $path)
			{
				if (file_exists($path.'helpers/'.$helper.'.php'))
				{
					//helper文件已经存在就加载
					include_once($path.'helpers/'.$helper.'.php');
					$this->_ci_helpers[$helper] = TRUE;
					log_message('debug', 'Helper loaded: '.$helper);
					break;
				}
			}
			if ( ! isset($this->_ci_helpers[$helper]))
			{
				show_error('Unable to load the requested file: helpers/'.$helper.'.php');
			}
		}
	}
	public function helpers($helpers = array())
	{
		$this->helper($helpers);
	}
	public function language($file = array(), $lang = '')
	{
		$CI =& get_instance();

		if ( ! is_array($file))
		{
			$file = array($file);
		}

		foreach ($file as $langfile)
		{
			$CI->lang->load($langfile, $lang);
		}
	}
	public function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
	{
		$CI =& get_instance();
		$CI->config->load($file, $use_sections, $fail_gracefully);
	}
	public function driver($library = '', $params = NULL, $object_name = NULL)
	{
		if ( ! class_exists('CI_Driver_Library'))
		{
			// we aren't instantiating an object here, that'll be done by the Library itself
			require BASEPATH.'libraries/Driver.php';
		}

		if ($library == '')
		{
			return FALSE;
		}

		// We can save the loader some time since Drivers will *always* be in a subfolder,
		// and typically identically named to the library
		if ( ! strpos($library, '/'))
		{
			$library = ucfirst($library).'/'.$library;
		}

		return $this->library($library, $params, $object_name);
	}
	public function add_package_path($path, $view_cascade=TRUE)
	{
		// 添加路径 
		$path = rtrim($path, '/').'/';

		array_unshift($this->_ci_library_paths, $path);
		array_unshift($this->_ci_model_paths, $path);
		array_unshift($this->_ci_helper_paths, $path);

		$this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths;

		// Add config file path
		$config =& $this->_ci_get_component('config');
		array_unshift($config->_config_paths, $path);
	}
	public function get_package_paths($include_base = FALSE)
	{
		return $include_base === TRUE ? $this->_ci_library_paths : $this->_ci_model_paths;
	}
	public function remove_package_path($path = '', $remove_config_path = TRUE)
	{
		// 删除指定的路径
		$config =& $this->_ci_get_component('config');

		if ($path == '')
		{
			$void = array_shift($this->_ci_library_paths);
			$void = array_shift($this->_ci_model_paths);
			$void = array_shift($this->_ci_helper_paths);
			$void = array_shift($this->_ci_view_paths);
			$void = array_shift($config->_config_paths);
		}
		else
		{
			$path = rtrim($path, '/').'/';
			foreach (array('_ci_library_paths', '_ci_model_paths', '_ci_helper_paths') as $var)
			{
				if (($key = array_search($path, $this->{$var})) !== FALSE)
				{
					unset($this->{$var}[$key]);
				}
			}

			if (isset($this->_ci_view_paths[$path.'views/']))
			{
				unset($this->_ci_view_paths[$path.'views/']);
			}

			if (($key = array_search($path, $config->_config_paths)) !== FALSE)
			{
				unset($config->_config_paths[$key]);
			}
		}

		// make sure the application default paths are still in the array
		$this->_ci_library_paths = array_unique(array_merge($this->_ci_library_paths, array(APPPATH, BASEPATH)));
		$this->_ci_helper_paths = array_unique(array_merge($this->_ci_helper_paths, array(APPPATH, BASEPATH)));
		$this->_ci_model_paths = array_unique(array_merge($this->_ci_model_paths, array(APPPATH)));
		$this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH.'views/' => TRUE));
		$config->_config_paths = array_unique(array_merge($config->_config_paths, array(APPPATH)));
	}
	/*
		加载文件 最主要的功能是加载view文件
	*/
	protected function _ci_load($_ci_data)
	{
		//初始化变量 不存在值就是FALSE
		foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
		{
			$$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val];
		}
		$file_exists = FALSE;//文件存在标志
		if ($_ci_path != '')
		{
			$_ci_x = explode('/', $_ci_path);
			$_ci_file = end($_ci_x);//文件名
		}
		else
		{
			$_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
			$_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view;//默认扩展名.php

			foreach ($this->_ci_view_paths as $view_file => $cascade) //遍历view path
			{
				if (file_exists($view_file.$_ci_file))
				{
					// 找到文件 设置 _ci_path 标志文件存在
					$_ci_path = $view_file.$_ci_file;
					$file_exists = TRUE;
					break;
				}
				if ( ! $cascade)
				{
					break;
				}
			}
		}
		if ( ! $file_exists && ! file_exists($_ci_path))
		{//没找到或者路径不存在
			show_error('Unable to load the requested file: '.$_ci_file);
		}
		$_ci_CI =& get_instance();
		foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
		{
			/*
				将CI类里面的对象绑定到本类
				也就是说 在 CI_Controller中调用class 可直接 $this->input->get('key')
				现在在CI_Loader里面同样能这样调用
			*/
			if ( ! isset($this->$_ci_key))
			{
				$this->$_ci_key =& $_ci_CI->$_ci_key;
			}
		}
		if (is_array($_ci_vars))
		{//合并_ci_vars 到 _ci_cached_vars
			$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
		}
		extract($this->_ci_cached_vars);

		// 激活缓冲区
		ob_start();
		if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE)
		{//替换 <?= 为 <?php echo 
			echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
		}
		else
		{
			// include() vs include_once() allows for multiple views with the same name
			include($_ci_path);
		}

		log_message('debug', 'File loaded: '.$_ci_path);
		if ($_ci_return === TRUE)
		{
			// 返回缓冲区内容
			// return buffer content
			$buffer = ob_get_contents();
			@ob_end_clean();
			return $buffer;
		}
		if (ob_get_level() > $this->_ci_ob_level + 1)
		{
			ob_end_flush();
		}
		else
		{
			// 合并多个缓冲区的内容
			$_ci_CI->output->append_output(ob_get_contents());
			@ob_end_clean();
		}
	}
	/*
		加载类
	*/
	protected function _ci_load_class($class, $params = NULL, $object_name = NULL)
	{
		$class = str_replace('.php', '', trim($class, '/'));
		$subdir = '';
		if (($last_slash = strrpos($class, '/')) !== FALSE)
		{
			$subdir = substr($class, 0, $last_slash + 1);//文件夹路径
			$class = substr($class, $last_slash + 1);//类文件名(没有后缀)
		}
		//两边查找 一遍首字母大写 一遍全小写
		foreach (array(ucfirst($class), strtolower($class)) as $class) 
		{
			//library的扩展class 文件路径
			$subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php';
			//扩展library class存在 找到基础类(被扩展的类)
			if (file_exists($subclass))
			{
				$baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php';
				if ( ! file_exists($baseclass))
				{//基础类不存在
					log_message('error', "Unable to load the requested class: ".$class);
					show_error("Unable to load the requested class: ".$class);
				}
				// subclass文件已经加载过 类的别名不空 并且名字不与CI成员属性发生冲突 实例化类并返回
				if (in_array($subclass, $this->_ci_loaded_files))
				{
					if ( ! is_null($object_name))
					{
						$CI =& get_instance();
						if ( ! isset($CI->$object_name))
						{
							return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
						}
					}
					$is_duplicate = TRUE;
					log_message('debug', $class." class already loaded. Second attempt ignored.");
					return;
				}
				// 加载基础类跟扩展类两个文件
				include_once($baseclass);
				include_once($subclass);
				$this->_ci_loaded_files[] = $subclass;//标记已经加载
				// 实例化class
				return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
			}
			$is_duplicate = FALSE;

			//遍历library路径
			foreach ($this->_ci_library_paths as $path) 
			{
				$filepath = $path.'libraries/'.$subdir.$class.'.php';
				if ( ! file_exists($filepath))
				{
					continue;//不存在继续找
				}
				//已加载过文件没什么问题就实例化
				if (in_array($filepath, $this->_ci_loaded_files))
				{
					if ( ! is_null($object_name))
					{
						$CI =& get_instance();
						if ( ! isset($CI->$object_name))
						{
							return $this->_ci_init_class($class, '', $params, $object_name);
						}
					}
					$is_duplicate = TRUE;
					log_message('debug', $class." class already loaded. Second attempt ignored.");
					return;
				}
				// 加载文件 标记已经加载 实例化class
				include_once($filepath);
				$this->_ci_loaded_files[] = $filepath;
				return $this->_ci_init_class($class, '', $params, $object_name);
			}

		}
		// 一次猜测尝试
		if ($subdir == '')
		{
			$path = strtolower($class).'/'.$class;
			return $this->_ci_load_class($path, $params);
		}
		if ($is_duplicate == FALSE)
		{
			log_message('error', "Unable to load the requested class: ".$class);
			show_error("Unable to load the requested class: ".$class);
		}
	}
	/*
		实例化class
	*/
	protected function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL)
	{
		if ($config === NULL)
		{
			// 实例化class的时候config作为实例化参数 为空用config class 加载对应class的配置文件 用参数实例化
			$config_component = $this->_ci_get_component('config');
			if (is_array($config_component->_config_paths))
			{
				foreach ($config_component->_config_paths as $path)
				{
					if (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'))
					{
						include($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php');
						break;
					}
					elseif (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'))
					{
						include($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php');
						break;
					}
					elseif (file_exists($path .'config/'.strtolower($class).'.php'))
					{
						include($path .'config/'.strtolower($class).'.php');
						break;
					}
					elseif (file_exists($path .'config/'.ucfirst(strtolower($class)).'.php'))
					{
						include($path .'config/'.ucfirst(strtolower($class)).'.php');
						break;
					}
				}
			}
		}

		if ($prefix == '')
		{
			// 加前缀 扩展前缀 不加前缀分别检测class是否存在
			if (class_exists('CI_'.$class))
			{
				$name = 'CI_'.$class;
			}
			elseif (class_exists(config_item('subclass_prefix').$class))
			{
				$name = config_item('subclass_prefix').$class;
			}
			else
			{
				$name = $class;
			}
		}
		else
		{
			$name = $prefix.$class;
		}
		if ( ! class_exists($name))
		{
			// 请求实例化的class不存在
			log_message('error', "Non-existent class: ".$name);
			show_error("Non-existent class: ".$class);
		}
		// class的名字都转变成了小写
		$class = strtolower($class);
		// 类的别名
		if (is_null($object_name))
		{
			$classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class];
		}
		else
		{
			$classvar = $object_name;
		}
		$this->_ci_classes[$class] = $classvar;//标记加载过
		// 实例化
		$CI =& get_instance();
		if ($config !== NULL)
		{
			$CI->$classvar = new $name($config);
		}
		else
		{
			$CI->$classvar = new $name;
		}
	}
	// 通过config里面的autoload实现自动加载
	private function _ci_autoloader()
	{
		if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'))
		{
			include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php');
		}
		else
		{
			include(APPPATH.'config/autoload.php');
		}
		if ( ! isset($autoload))
		{
			return FALSE;
		}
		if (isset($autoload['packages']))
		{
			foreach ($autoload['packages'] as $package_path)
			{
				$this->add_package_path($package_path);
			}
		}
		if (count($autoload['config']) > 0)
		{
			$CI =& get_instance();
			foreach ($autoload['config'] as $key => $val)
			{
				$CI->config->load($val);
			}
		}
		foreach (array('helper', 'language') as $type)
		{
			if (isset($autoload[$type]) AND count($autoload[$type]) > 0)
			{
				$this->$type($autoload[$type]);
			}
		}
		if ( ! isset($autoload['libraries']) AND isset($autoload['core']))
		{
			// 出现名称冲突 优先加载core
			$autoload['libraries'] = $autoload['core'];
		}
		if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0)
		{
			if (in_array('database', $autoload['libraries']))
			{
				$this->database();
				$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
			}
			foreach ($autoload['libraries'] as $item)
			{
				$this->library($item);
			}
		}
		if (isset($autoload['model']))
		{
			$this->model($autoload['model']);
		}
	}
	// string get_object_vars() 字符串的形式返回对象变量
	protected function _ci_object_to_array($object)
	{
		return (is_object($object)) ? get_object_vars($object) : $object;
	}
	protected function &_ci_get_component($component)
	{
		$CI =& get_instance();
		return $CI->$component;
	}
	/*
	1、str_replace('_helper','',filename) myHelper_helper.php-->myHelper.php
	2、str_replace('.php','',filename) myHelper.php-->myHelper
	3、array(myhelper_helper);
	整个过程是把helper函数的文件名称初始化成 name_helper
	*/
	protected function _ci_prep_filename($filename, $extension)
	{
		if ( ! is_array($filename))
		{
			return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension));
		}
		else
		{
			foreach ($filename as $key => $val)
			{
				$filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $val)).$extension);
			}
			return $filename;
		}
	}
}


这是几个常用的方法:
/*
is_loaded
library
model
view
file
helper
language
config
vars
get_var


add_package_path
get_package_paths
remove_package_path

_ci_load 		加载文件 		主要用于view
_ci_load_class	加载class 		主要用于library
_ci_init_class	实例化class 	主要被_ci_load_class 调用
_ci_autoloader	自动加载
*/

Code Tips :

后面的4个函数写法很值得借鉴 还有就是package的设计思路值得学习

特别是library的加载 通过检测_ci_load_file 检测文件是否已经加载 已经加载的class只需要实例化就ok

_ci_init_class 里面的通过配置文件实例化class的设计方式值得借鉴

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章