本文实例分析了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参数指定需要加载的文件,注意$filename不需要指定任何路径,只需要文件名即可。zf会对文件作安全性检查。$filename 只能由字母,数字,连接符-,下划线_及英文句号.组成(半角)。$dirs参数则不限,可以使用中文等。
$dirs 参数用来指定文件所在目录,可以是一个字符串或者数组。如果为 null,则程序将会到系统的 include_path 下寻找文件是否存在(include_path可在php.ini中设置--haohappy注),如果是字符串或数组,则会到指定的目录下去找,然后才是 include_path。
$once 参数为布尔类型,如果为 true,zend_loader::loadfile() 使用 php 函数 » include_once() 加载文件,否则就是 php 函数 » include()。(本参数只能是true或false,两者区别就和include()和include_once()的区别一样。)
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()封装而成的,is_readable() 不会自动查找 include_path 下的文件,而 zend::isreadable() 可以。
4.autoloader
这个类的autoloader功能已经不推荐使用了,所以不再讲述。还有其他的autoloader,以后具体说明。
5.插件加载器
帮助文章给出的具体实例如下,可参考使用:
很多 zend framework 组件支持插件,允许通过指定类的前缀和到类的文件(不需要在 include_path或不需要遵循传统命名约定的文件)的路径动态加载函数。zend_loader_pluginloader 提供了普通的函数来完成这个工作。
pluginloader 的基本用法遵循 zend framework 的命名约定(一个文件一个类),解析路径时,使用下划线作为路径分隔符。当决定是否加载特别的插件类,允许传递可选的类前缀来预处理。另外,路径按 lifo 顺序来搜索。由于 lifo 搜索和类的前缀,允许命名空间给插件,这样可以从早期注册的路径来覆盖插件。
基本用例
首先,假定下面的目录结构和类文件,并且根(toplevel)目录和库目录在 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'
?>
类加载后,就可以实例化了。
note: 为一个前缀注册多个路径
有时候,多个路径使用相同的前缀,zend_loader_pluginloader 实际上为每个给定的前缀注册一个路径数组;最后注册的被首先检查,当你使用孵化器里的组件时,这相当有用。
note: 实例化时定义路径
你可以提供给构造器一个可选的“前缀/路径”对(或“前缀/多个路径”)数组参数:
<?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,getpaths($prefix = null) 返回为给定的前缀注册的路径。
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。这里不在累述。
更多关于zend相关内容感兴趣的读者可查看本站专题:《zend framework框架入门教程》、《php优秀开发框架总结》、《yii框架入门及常用技巧总结》、《thinkphp入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!