Zend Framework Loader与PluginLoader概述
本实例深入剖析了Zend Framework中Loader与PluginLoader的具体应用方式,旨在为开发者提供实用的参考指南。
在Zend Framework框架内,Zend_Loader模块专门负责处理文件的动态加载任务。
下文将展示其具体调用方法及底层实现逻辑。
1. 加载文件功能
调用方式如下:
Zend_Loader::loadFile($filename, $dirs=null, $once=false);
核心实现代码见下:
/**
* Loads a PHP file. This is a wrapper for PHP's include() function.
*
* $filename must be the complete filename, including any
* extension such as ".php". Note that a security check is performed that
* does not permit extended characters in the filename. This method is
* intended for loading Zend Framework files.
*
* If $dirs is a string or an array, it will search the directories
* in the order supplied, and attempt to load the first matching file.
*
* If the file was not found in the $dirs, or if no $dirs were specified,
* it will attempt to load it from PHP's include_path.
*
* If $once is TRUE, it will use include_once() instead of include().
*
* @param string $filename
* @param string|array $dirs - OPTIONAL either a path or array of paths
* to search.
* @param boolean $once
* @return boolean
* @throws Zend_Exception
*/
public static function loadFile($filename, $dirs = null, $once = false)
{
self::_securityCheck($filename);
/**
* Search in provided directories, as well as include_path
*/
$incPath = false;
if (!empty($dirs) && (is_array($dirs) || is_string($dirs))) {
if (is_array($dirs)) {
$dirs = implode(PATH_SEPARATOR, $dirs);
}
$incPath = get_include_path();
set_include_path($dirs . PATH_SEPARATOR . $incPath);
}
/**
* Try finding for the plain filename in the include_path.
*/
if ($once) {
include_once $filename;
} else {
include $filename;
}
/**
* If searching in directories, reset include_path
*/
if ($incPath) {
set_include_path($incPath);
}
return true;
}
参数设定规范:
依据上述实现逻辑,主要涉及以下参数说明
$filename参数用于指定待加载的文件名,无需包含路径信息,仅填写文件名即可。ZF内部会对该文件名执行安全校验。$filename仅允许包含半角字母、数字、连接符-、下划线_及英文句号.。$dirs参数则无此限制,支持中文等字符。
$dirs参数用于指定文件所在的目录,可接受字符串或数组格式。若设为NULL,程序将自动在系统的include_path(可在php.ini中配置)中搜索文件;若为字符串或数组,则优先在指定目录中查找,随后才回退至include_path。
$once参数为布尔类型。若为TRUE,Zend_Loader::loadFile()将调用PHP的include_once()函数加载文件;否则使用include()。此参数仅接受true或false,其作用等同于PHP原生函数的区别。
2. 加载类功能
具体调用示例:
Zend_Loader::loadClass('Container_Tree',
array(
'/home/production/mylib',
'/home/production/myapp'
)
);
具体实现逻辑:
/**
* Loads a class from a PHP file. The filename must be formatted
* as "$class.php".
*
* If $dirs is a string or an array, it will search the directories
* in the order supplied, and attempt to load the first matching file.
*
* If $dirs is null, it will split the class name at underscores to
* generate a path hierarchy (e.g., "Zend_Example_Class" will map
* to "Zend/Example/Class.php").
*
* If the file was not found in the $dirs, or if no $dirs were specified,
* it will attempt to load it from PHP's include_path.
*
* @param string $class - The full class name of a Zend component.
* @param string|array $dirs - OPTIONAL Either a path or an array of paths
* to search.
* @return void
* @throws Zend_Exception
*/
public static function loadClass($class, $dirs = null)
{
if (class_exists($class, false) || interface_exists($class, false)) {
return;
}
if ((null !== $dirs) && !is_string($dirs) && !is_array($dirs)) {
require_once 'Zend/Exception.php';
throw new Zend_Exception('Directory argument must be a string or an array');
}
// Autodiscover the path from the class name
// Implementation is PHP namespace-aware, and based on
// Framework Interop Group reference implementation:
// http://groups.google.com/group/php-standards/web/psr-0-final-proposal
$className = ltrim($class, '\\');
$file = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$file .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if (!empty($dirs)) {
// use the autodiscovered path
$dirPath = dirname($file);
if (is_string($dirs)) {
$dirs = explode(PATH_SEPARATOR, $dirs);
}
foreach ($dirs as $key => $dir) {
if ($dir == '.') {
$dirs[$key] = $dirPath;
} else {
$dir = rtrim($dir, '\\/');
$dirs[$key] = $dir . DIRECTORY_SEPARATOR . $dirPath;
}
}
$file = basename($file);
self::loadFile($file, $dirs, true);
} else {
self::loadFile($file, null, true);
}
if (!class_exists($class, false) && !interface_exists($class, false)) {
require_once 'Zend/Exception.php';
throw new Zend_Exception("File \"$file\" does not exist or class \"$class\" was not found in the file");
}
}
$class类名将依据下划线作为目录分隔符映射到对应的PHP文件,并自动追加'.php'后缀,例如Container_Tree对应Container/Tree.php。 $dir参数可为数组或字符串,表示除类名隐含路径外的基础目录路径。
3. 检测文件是否可读
具体调用示例:
if (Zend_Loader::isReadable($filename)) {
// do something with $filename
}
具体实现逻辑:
/**
* Returns TRUE if the $filename is readable, or FALSE otherwise.
* This function uses the PHP include_path, where PHP's is_readable()
* does not.
*
* Note from ZF-2900:
* If you use custom error handler, please check whether return value
* from error_reporting() is zero or not.
* At mark of fopen() can not suppress warning if the handler is used.
*
* @param string $filename
* @return boolean
*/
public static function isReadable($filename)
{
if (is_readable($filename)) {
// Return early if the filename is readable without needing the
// include_path
return true;
}
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'
&& preg_match('/^[a-z]:/i', $filename)
) {
// If on windows, and path provided is clearly an absolute path,
// return false immediately
return false;
}
foreach (self::explodeIncludePath() as $path) {
if ($path == '.') {
if (is_readable($filename)) {
return true;
}
continue;
}
$file = $path . '/' . $filename;
if (is_readable($file)) {
return true;
}
}
return false;
}
具体参数说明:
$filename参数指定需检查的文件名,包含完整路径信息。该方法封装了PHP的is_readable()函数,但不同之处在于,Zend::isReadable()会自动在include_path中查找文件,而原生函数不会。
4. Autoloader机制
该类原有的Autoloader功能已不再推荐,故此处略过。其他类型的Autoloader将在后续章节详细说明。
5. 插件加载器
官方文档提供的具体实例如下,供参考使用:
许多Zend Framework组件支持插件机制,允许通过指定类的前缀及文件路径(无需遵循include_path或传统命名约定)来动态加载函数。Zend_Loader_PluginLoader提供了通用的函数接口以完成此项工作。
PluginLoader的基本用法遵循Zend Framework的命名约定(单文件单类),解析路径时使用下划线作为分隔符。在决定是否加载特定插件类时,允许传递可选的类前缀进行预处理。此外,路径按LIFO(后进先出)顺序进行搜索。结合LIFO搜索与类前缀机制,可以为插件定义命名空间,从而允许从早期注册的路径中覆盖插件。
基本用例演示
首先,假设存在以下目录结构和类文件,且根目录和库目录已加入include_path:
application/ modules/ foo/ views/ helpers/ FormLabel.php FormSubmit.php bar/ views/ helpers/ FormSubmit.php library/ Zend/ View/ Helper/ FormLabel.php FormSubmit.php FormText.php
接下来,创建一个插件加载器以启用各种视图助手仓库:
<?php
$loader = new Zend_Loader_PluginLoader();
$loader->addPrefixPath('Zend_View_Helper', 'Zend/View/Helper/')
->addPrefixPath('Foo_View_Helper', 'application/modules/foo/views/helpers')
->addPrefixPath('Bar_View_Helper', 'application/modules/bar/views/helpers');
?>
随后,利用类名中添加路径时定义的前缀之后的部分来加载指定的视图助手:
<?php
// load 'FormText' helper:
$formTextClass = $loader->load('FormText'); // 'Zend_View_Helper_FormText';
// load 'FormLabel' helper:
$formLabelClass = $loader->load('FormLabel'); // 'Foo_View_Helper_FormLabel'
// load 'FormSubmit' helper:
$formSubmitClass = $loader->load('FormSubmit'); // 'Bar_View_Helper_FormSubmit'
?>
类加载完成后,即可进行实例化操作。
注意:为一个前缀注册多个路径
有时多个路径会使用相同的前缀,此时Zend_Loader_PluginLoader实际上会为每个给定前缀注册一个路径数组;最后注册的路径会被最先检查,这在配合孵化器组件使用时非常有用。
注意:实例化时定义路径
你可以向构造器提供一个可选的“前缀/路径”对(或“前缀/多个路径”)数组参数:
<?php
$loader = new Zend_Loader_PluginLoader(array(
'Zend_View_Helper' => 'Zend/View/Helper/',
'Foo_View_Helper' => 'application/modules/foo/views/helpers',
'Bar_View_Helper' => 'application/modules/bar/views/helpers'
));
?>
Zend_Loader_PluginLoader在无需使用单态实例的情况下,也支持通过静态注册表共享插件,这需要在实例化时将注册表名作为构造器的第二个参数传入:
<?php
// Store plugins in static registry 'foobar':
$loader = new Zend_Loader_PluginLoader(array(), 'foobar');
?>
其他使用同名注册表实例化PluginLoader的组件,将能够访问已加载的路径和插件。
处理插件路径
上节的示例展示了如何向插件加载器添加路径,那么如何确定已加载的路径或删除它们呢?
若未提供$prefix,getPaths($prefix = null)将以“前缀/路径”对的形式返回所有路径;若提供了$prefix,则返回为该前缀注册的路径。
clearPaths($prefix = null)默认清除所有已注册路径,或者如果提供了$prefix并将其置于堆栈中,则仅清除与该给定前缀关联的路径。
removePrefixPath($prefix, $path = null)允许有选择地清除与给定前缀相关的特定路径。若未提供$path,则清除所有与前缀相关的路径;若提供了$path且相应前缀存在,则仅清除该特定路径。 测试插件状态及获取类名
有时你需要在执行动作前确认插件类是否已加载,isLoaded()可返回插件名的当前状态。
PluginLoader的另一个常见用例是确定已加载类的完全限定插件类名,getClassName()提供此功能。通常它与isLoaded()联合使用:
<?php
if ($loader->isLoaded('Adapter')) {
$class = $loader->getClassName('Adapter');
$adapter = call_user_func(array($class, 'getInstance'));
}
?>
关于插件加载器的具体实现细节,可参考Zend_Loader_PluginLoader和Zend_Loader源码,此处不再赘述。
希望本文所述内容能对大家的PHP程序设计有所帮助。