cakephp 中spl_autoload_register用法

使用spl_autoload_register() 自定义的方法来加载文件语法:bool spl_autoload_register ( [callback $autoload_function] ) 

1.在cakephp中使用(bootstrap.php):

1).通过数组的形式传递类和方法,元素一为类名称、元素二为方法名称

2).方法为静态方法

spl_autoload_register(array('App', 'load'));

2.App下的load方法(core/App.php)

/**
 * 处理自动加载类的方法.它会找到每个类包
 * 使用App::uses()来定义并且带有解决全路径包名的信息
 * 每个类







文件



名称



应遵循



的类的名称








 * 例如:类名`MyCustomClass` 文件 `MyCustomClass.php`

 * @param string $className the name of the class to load
 * @return boolean
 */
	public static function load($className) {
               //protected static $_classMap = array(); 通过App::uses()加入的: $className=>$location
                if (!isset(self::$_classMap[$className])) {
			return false;
		}
		if ($file = self::_mapped($className)) {
			return include $file;
		}
                //用点号分开plugin文件夹
		$parts = explode('.', self::$_classMap[$className], 2);
		list($plugin, $package) = count($parts) > 1 ? $parts : array(null, current($parts));
		$paths = self::path($package, $plugin);

		if (empty($plugin)) {
			$appLibs = empty(self::$_packages['Lib']) ? APPLIBS : current(self::$_packages['Lib']);
			//优先app lib
                        $paths[] =  $appLibs . $package . DS;
			$paths[] = CAKE . $package . DS;
		}

		foreach ($paths as $path) {
			$file = $path . $className . '.php';
			if (file_exists($file)) {
				self::_map($file, $className);
                                return include $file; //include file and can new class
			}
		}

		//To help apps migrate to 2.0 old style file names are allowed
		foreach ($paths as $path) {
			$underscored = Inflector::underscore($className);
			$tries = array($path . $underscored . '.php');
			$parts = explode('_', $underscored);
			if (count($parts) > 1) {
				array_pop($parts);
				$tries[] = $path . implode('_', $parts) . '.php';
			}
			foreach ($tries as $file) {
				if (file_exists($file)) {
					self::_map($file, $className);
					return include $file;
				}
			}
		}

		return false;
	}

3.

扫描二维码关注公众号,回复: 765966 查看本文章
App::uses('Dispatcher', 'Routing');

$Dispatcher = new Dispatcher();
	
$Dispatcher->dispatch(new CakeRequest(), new CakeResponse(array('charset' => Configure::read('App.encoding'))));
 

猜你喜欢

转载自ieric.iteye.com/blog/1256325
今日推荐