background image

PHP 工具:Zend 的 AutoLoad 机制介绍

在使用 zend framework 的时候,最先引入的一定是 AutoLoad 的机制,这里就想分析下
Zend 的 AutoLoad 是怎么引入的

 

代码示例
 
代码如下:
 
set_include_path(USVN_LIB_DIR . PATH_SEPARATOR . get_include_path()); 

require_once

 'Zend/Loader/Autoloader.php'; 

$autoloader

 = Zend_Loader_Autoloader::getInstance(); 

$autoloader

->registerNamespace("Zend_"); 

$autoloader

->registerNamespace("USVN_"); 

$autoloader

->registerNamespace("menus_"); 

$config

 = 

new

 USVN_Config_Ini(USVN_CONFIG_FILE, USVN_CONFIG_SECTION); 

 
 

 

过程分析
 
首先是设置了 include_path,include_path 就是 php 中调用

include

 

的时候文件寻找的地址

 

下面就是

require_once

 'Zend/Loader/Autoloader.php'; 

 
在 Zend/Loader/Autoloader.php 文件内,读入了 Zend/Loader.php  

, 这个 php 定义了

Zend_Loader 这个类,这个类包含了 loadClass,loadFile, isReadable(文件是否可读)

 

等函数

实例化 Zend_Loader_Autoloader 的过程就是调用其构造函数(这里是使用了单例模式)的

 

过程
 
它的构造函数中的 spl_autoload_register(

array

(

__CLASS__

, 'autoload'));将

Zend_Loader_Autoloader:autoload

 

作为类自动加载函数。

还做了一个操作将_internalAutoloader 赋值了自身的_autoload 
 
至于这里面是怎么 autoload

 

的等会根据具体例子查看

接下来调用了 Zend_Loader_Autoloader:registerNamespace("USVN_"),这个函数做的事就只
是在 Zend_Loader_AutoLoader 的内部属性_namespaces 上挂载一个 key 为 USVN_和 value
为 true

 

的值。

 

 

看到这个函数就明白其实代码也可以写成
 

$autoloader

->registerNamespace("Zend_")->registerNamespace("USVN_") 

 

或者

$autoloader

->registerNamespace(

array

("Zend_","USVN_"))