搜索
首页后端开发php教程Zend Framework教程之Loader以及PluginLoader用法详解_PHP

本文实例分析了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

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

<&#63;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');
&#63;>

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

<&#63;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'
&#63;>

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

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

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

Note: 实例化时定义路径

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

<&#63;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'
));
&#63;>

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

<&#63;php
// Store plugins in static registry 'foobar':
$loader = new Zend_Loader_PluginLoader(array(), 'foobar');
&#63;>

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

处理插件路径

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

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

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

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

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

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

<&#63;php
if ($loader->isLoaded('Adapter')) {
  $class  = $loader->getClassName('Adapter');
  $adapter = call_user_func(array($class, 'getInstance'));
}
&#63;>

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

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

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

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Microsoft NET Framework 安装问题 错误代码 0x800c0006 修复Microsoft NET Framework 安装问题 错误代码 0x800c0006 修复May 05, 2023 pm 04:01 PM

.NETFramework4是开发人员和最终用户在Windows上运行最新版本的应用程序所必需的。但是,在下载安装.NETFramework4时,许多用户抱怨安装程序在中途停止,显示以下错误消息-“ .NETFramework4hasnotbeeninstalledbecauseDownloadfailedwitherrorcode0x800c0006 ”。在您的设备上安装.NETFramework4时,如果您也在体验它,那么您就来对了地方

如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题Apr 17, 2023 am 10:07 AM

每当您的Windows11或Windows10PC出现升级或更新问题时,您通常会看到一个错误代码,指示故障背后的实际原因。但是,有时,升级或更新失败可能不会显示错误代码,这时就会出现混淆。有了方便的错误代码,您就可以确切地知道问题出在哪里,因此您可以尝试修复。但是由于没有出现错误代码,因此识别问题并解决它变得极具挑战性。这会占用您大量时间来简单地找出错误背后的原因。在这种情况下,您可以尝试使用Microsoft提供的名为SetupDiag的专用工具,该工具可帮助您轻松识别错误背后的真

SCNotification 已停止工作 [修复它的 5 个步骤]SCNotification 已停止工作 [修复它的 5 个步骤]May 17, 2023 pm 09:35 PM

作为Windows用户,您很可能会在每次启动计算机时遇到SCNotification已停止工作错误。SCNotification.exe是一个微软系统通知文件,由于权限错误和点网故障等原因,每次启动PC时都会崩溃。此错误也以其问题事件名称而闻名。因此,您可能不会将其视为SCNotification已停止工作,而是将其视为错误clr20r3。在本文中,我们将探讨您需要采取的所有步骤来修复SCNotification已停止工作,以免它再次困扰您。什么是SCNotification.e

Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Apr 17, 2023 pm 02:25 PM

已安装Microsoft.NET版本4.5.2、4.6或4.6.1的MicrosoftWindows用户如果希望Microsoft将来通过产品更新支持该框架,则必须安装较新版本的Microsoft框架。据微软称,这三个框架都将在2022年4月26日停止支持。支持日期结束后,产品将不会收到“安全修复或技术支持”。大多数家庭设备通过Windows更新保持最新。这些设备已经安装了较新版本的框架,例如.NETFramework4.8。未自动更新的设备可能

适用于 Windows 11 的KB5012643破坏了.NET Framework 3.5应用程序适用于 Windows 11 的KB5012643破坏了.NET Framework 3.5应用程序May 09, 2023 pm 01:07 PM

自我们谈论影响安装KB5012643forWindows11的用户的新安全模式错误以来已经过去了一周。这个讨厌的问题并没有出现在微软在发布当天发布的已知问题列表中,因此让所有人都感到意外。好吧,就在您认为情况不会变得更糟的时候,微软为安装此累积更新的用户投下了另一颗炸弹。Windows11Build22000.652导致更多问题因此,这家科技公司警告Windows11用户,他们在启动和使用某些.NETFramework3.5应用程序时可能会遇到问题。听起来很熟悉?不过请不要惊

如何在Zend框架中使用ACL(Access Control List)进行权限控制如何在Zend框架中使用ACL(Access Control List)进行权限控制Jul 29, 2023 am 09:24 AM

如何在Zend框架中使用ACL(AccessControlList)进行权限控制导言:在一个Web应用程序中,权限控制是至关重要的一项功能。它可以确保用户只能访问其有权访问的页面和功能,并防止未经授权的访问。Zend框架提供了一种方便的方法来实现权限控制,即使用ACL(AccessControlList)组件。本文将介绍如何在Zend框架中使用ACL

PHP实现框架:Zend Framework入门教程PHP实现框架:Zend Framework入门教程Jun 19, 2023 am 08:09 AM

PHP实现框架:ZendFramework入门教程ZendFramework是PHP开发的一种开源网站框架,目前由ZendTechnologies维护,ZendFramework采用了MVC设计模式,提供了一系列可重用的代码库,服务于实现Web2.0应用程序和Web服务。ZendFramework深受PHP开发者的欢迎和推崇,拥有广泛

酷冷至尊携手Framework推出创新迷你机箱套件,兼容笔记本主板酷冷至尊携手Framework推出创新迷你机箱套件,兼容笔记本主板Dec 15, 2023 pm 05:35 PM

12月9日消息,最近,酷冷至尊在台北电脑展上的一次展示活动中,展示了与笔记本模块化方案提供商framework合作的迷你机箱套件,这个套件的独特之处在于,它可以兼容并安装来自framework笔记本的主板。目前,这款产品已经开始在市场上销售,售价定为39美元,按当前汇率折合大约279元人民币。这款机箱套件的型号被命名为“frameWORKMAINBOARDCASE”。在设计方面,它体现了极致的紧凑与实用性,尺寸仅为297x133x15毫米。它的设计初衷是为了能够无缝接入framework笔记本的

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具