当前位置:Gxlcms > php框架 > Zend Framework教程之Loader以及PluginLoader用法详解

Zend Framework教程之Loader以及PluginLoader用法详解

时间:2021-07-01 10:21:17 帮助过:36人阅读

本文实例分析了Zend Framework中Loader以及PluginLoader用法。分享给大家供大家参考,具体如下:

Zend Framework提供了Zend_Loader,用来动态加载文件。

以下是具体用法,以及具体实现:

1.加载文件

使用方法:

  1. Zend_Loader::loadFile($filename, $dirs=null, $once=false);

具体实现:

  1. /**
  2. * Loads a PHP file. This is a wrapper for PHP's include() function.
  3. *
  4. * $filename must be the complete filename, including any
  5. * extension such as ".php". Note that a security check is performed that
  6. * does not permit extended characters in the filename. This method is
  7. * intended for loading Zend Framework files.
  8. *
  9. * If $dirs is a string or an array, it will search the directories
  10. * in the order supplied, and attempt to load the first matching file.
  11. *
  12. * If the file was not found in the $dirs, or if no $dirs were specified,
  13. * it will attempt to load it from PHP's include_path.
  14. *
  15. * If $once is TRUE, it will use include_once() instead of include().
  16. *
  17. * @param string $filename
  18. * @param string|array $dirs - OPTIONAL either a path or array of paths
  19. * to search.
  20. * @param boolean $once
  21. * @return boolean
  22. * @throws Zend_Exception
  23. */
  24. public static function loadFile($filename, $dirs = null, $once = false)
  25. {
  26. self::_securityCheck($filename);
  27. /**
  28. * Search in provided directories, as well as include_path
  29. */
  30. $incPath = false;
  31. if (!empty($dirs) && (is_array($dirs) || is_string($dirs))) {
  32. if (is_array($dirs)) {
  33. $dirs = implode(PATH_SEPARATOR, $dirs);
  34. }
  35. $incPath = get_include_path();
  36. set_include_path($dirs . PATH_SEPARATOR . $incPath);
  37. }
  38. /**
  39. * Try finding for the plain filename in the include_path.
  40. */
  41. if ($once) {
  42. include_once $filename;
  43. } else {
  44. include $filename;
  45. }
  46. /**
  47. * If searching in directories, reset include_path
  48. */
  49. if ($incPath) {
  50. set_include_path($incPath);
  51. }
  52. return true;
  53. }

参数规则:

正如实现方法,有如下参数

$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.加载类

具体使用:

  1. Zend_Loader::loadClass('Container_Tree',
  2. array(
  3. '/home/production/mylib',
  4. '/home/production/myapp'
  5. )
  6. );

具体实现:

  1. /**
  2. * Loads a class from a PHP file. The filename must be formatted
  3. * as "$class.php".
  4. *
  5. * If $dirs is a string or an array, it will search the directories
  6. * in the order supplied, and attempt to load the first matching file.
  7. *
  8. * If $dirs is null, it will split the class name at underscores to
  9. * generate a path hierarchy (e.g., "Zend_Example_Class" will map
  10. * to "Zend/Example/Class.php").
  11. *
  12. * If the file was not found in the $dirs, or if no $dirs were specified,
  13. * it will attempt to load it from PHP's include_path.
  14. *
  15. * @param string $class - The full class name of a Zend component.
  16. * @param string|array $dirs - OPTIONAL Either a path or an array of paths
  17. * to search.
  18. * @return void
  19. * @throws Zend_Exception
  20. */
  21. public static function loadClass($class, $dirs = null)
  22. {
  23. if (class_exists($class, false) || interface_exists($class, false)) {
  24. return;
  25. }
  26. if ((null !== $dirs) && !is_string($dirs) && !is_array($dirs)) {
  27. require_once 'Zend/Exception.php';
  28. throw new Zend_Exception('Directory argument must be a string or an array');
  29. }
  30. // Autodiscover the path from the class name
  31. // Implementation is PHP namespace-aware, and based on
  32. // Framework Interop Group reference implementation:
  33. // http://groups.google.com/group/php-standards/web/psr-0-final-proposal
  34. $className = ltrim($class, '\\');
  35. $file = '';
  36. $namespace = '';
  37. if ($lastNsPos = strripos($className, '\\')) {
  38. $namespace = substr($className, 0, $lastNsPos);
  39. $className = substr($className, $lastNsPos + 1);
  40. $file = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
  41. }
  42. $file .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
  43. if (!empty($dirs)) {
  44. // use the autodiscovered path
  45. $dirPath = dirname($file);
  46. if (is_string($dirs)) {
  47. $dirs = explode(PATH_SEPARATOR, $dirs);
  48. }
  49. foreach ($dirs as $key => $dir) {
  50. if ($dir == '.') {
  51. $dirs[$key] = $dirPath;
  52. } else {
  53. $dir = rtrim($dir, '\\/');
  54. $dirs[$key] = $dir . DIRECTORY_SEPARATOR . $dirPath;
  55. }
  56. }
  57. $file = basename($file);
  58. self::loadFile($file, $dirs, true);
  59. } else {
  60. self::loadFile($file, null, true);
  61. }
  62. if (!class_exists($class, false) && !interface_exists($class, false)) {
  63. require_once 'Zend/Exception.php';
  64. throw new Zend_Exception("File \"$file\" does not exist or class \"$class\" was not found in the file");
  65. }
  66. }

$class 类名将会根据下划线(作为目录分隔线)对应到相应目录下的PHP文件,并加上'.php',比如Container_Tree会指向Container\\Tree.php。
$dir     可以是数组或者字符串。目录是除去类名包含的目录的路径。

3.判断某个文件是否可读

具体使用:

  1. if (Zend_Loader::isReadable($filename)) {
  2. // do something with $filename
  3. }

具体实现:

  1. /**
  2. * Returns TRUE if the $filename is readable, or FALSE otherwise.
  3. * This function uses the PHP include_path, where PHP's is_readable()
  4. * does not.
  5. *
  6. * Note from ZF-2900:
  7. * If you use custom error handler, please check whether return value
  8. * from error_reporting() is zero or not.
  9. * At mark of fopen() can not suppress warning if the handler is used.
  10. *
  11. * @param string $filename
  12. * @return boolean
  13. */
  14. public static function isReadable($filename)
  15. {
  16. if (is_readable($filename)) {
  17. // Return early if the filename is readable without needing the
  18. // include_path
  19. return true;
  20. }
  21. if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'
  22. && preg_match('/^[a-z]:/i', $filename)
  23. ) {
  24. // If on windows, and path provided is clearly an absolute path,
  25. // return false immediately
  26. return false;
  27. }
  28. foreach (self::explodeIncludePath() as $path) {
  29. if ($path == '.') {
  30. if (is_readable($filename)) {
  31. return true;
  32. }
  33. continue;
  34. }
  35. $file = $path . '/' . $filename;
  36. if (is_readable($file)) {
  37. return true;
  38. }
  39. }
  40. return false;
  41. }

具体参数:

$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

现在,创建一个插件加载器来使各种各样的视图助手仓库可用:

  1. <?php
  2. $loader = new Zend_Loader_PluginLoader();
  3. $loader->addPrefixPath('Zend_View_Helper', 'Zend/View/Helper/')
  4. ->addPrefixPath('Foo_View_Helper', 'application/modules/foo/views/helpers')
  5. ->addPrefixPath('Bar_View_Helper', 'application/modules/bar/views/helpers');
  6. ?>

接着用类名中添加路径时定义的前缀后面的部分来加载一个给定的视图助手:

  1. <?php
  2. // load 'FormText' helper:
  3. $formTextClass = $loader->load('FormText'); // 'Zend_View_Helper_FormText';
  4. // load 'FormLabel' helper:
  5. $formLabelClass = $loader->load('FormLabel'); // 'Foo_View_Helper_FormLabel'
  6. // load 'FormSubmit' helper:
  7. $formSubmitClass = $loader->load('FormSubmit'); // 'Bar_View_Helper_FormSubmit'
  8. ?>

类加载后,就可以实例化了。

Note: 为一个前缀注册多个路径

有时候,多个路径使用相同的前缀,Zend_Loader_PluginLoader 实际上为每个给定的前缀注册一个路径数组;最后注册的被首先检查,当你使用孵化器里的组件时,这相当有用。

Note: 实例化时定义路径

你可以提供给构造器一个可选的“前缀/路径”对(或“前缀/多个路径”)数组参数:

  1. <?php
  2. $loader = new Zend_Loader_PluginLoader(array(
  3. 'Zend_View_Helper' => 'Zend/View/Helper/',
  4. 'Foo_View_Helper' => 'application/modules/foo/views/helpers',
  5. 'Bar_View_Helper' => 'application/modules/bar/views/helpers'
  6. ));
  7. ?>

Zend_Loader_PluginLoader 在不需要使用单态实例的情况下,也可选地允许共享插件,这是通过静态注册表来完成的,在实例化时需要注册表名作为构造器的第二个参数:

  1. <?php
  2. // Store plugins in static registry 'foobar':
  3. $loader = new Zend_Loader_PluginLoader(array(), 'foobar');
  4. ?>

其它使用同名注册表来实例化 PluginLoader 的组件将可以访问已经加载的路径和插件。

处理插件路径

上节的例子示例如何给插件加载器添加路径,那么如何确定已经加载的路径或删除他们呢?

如果没有提供 $prefix,getPaths($prefix = null) 以“前缀/路径”对返回所有的路径;或者如果提供了 $prefix,getPaths($prefix = null) 返回为给定的前缀注册的路径。

clearPaths($prefix = null) 将缺省地清除所有的已注册路径,或者如果提供了 $prefix 并放在堆栈里,只清除和那些和给定前缀关联的路径。

removePrefixPath($prefix, $path = null) 允许有选择地清除和给定前缀相关的特定的路径。如果没有提供 $path ,所有的和前缀相关的路径被清除,如果提供了 $path 并且相应的前缀存在,只有这个相关的路径被清除。
测试插件和获取类的名字

有时候你想确定在执行一个动作之前是否插件类已经加载,isLoaded() 返回插件名的状态。

PluginLoader 的另一个普通用例是确定已加载类的完全合格的插件类名,getClassName() 提供该功能。一般地,这个和 isLoaded() 联合使用:

  1. <?php
  2. if ($loader->isLoaded('Adapter')) {
  3. $class = $loader->getClassName('Adapter');
  4. $adapter = call_user_func(array($class, 'getInstance'));
  5. }
  6. ?>

具体插件加载器的实现可以参考Zend_Loader_PluginLoader和Zend_Loader。这里不在累述。

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

人气教程排行