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的設計方式值得借鑑

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