How to Use Loader and PluginLoader in ZendFramework

Source: Internet
Author: User
Tags autoloader zend framework
This document analyzes the usage of Loader and PluginLoader in ZendFramework. For your reference, ZendFramework provides Zend_Loader to dynamically load files. The usage is as follows: 1. how to load a file: Zend_Loader: loadFile ($ filename, $ dirsnull

This article analyzes the usage of Loader and PluginLoader in Zend Framework. For your reference, the Zend Framework provides Zend_Loader to dynamically load files. The usage is as follows: 1. how to load a file: Zend_Loader: loadFile ($ filename, $ dirs = null

This article analyzes the usage of Loader and PluginLoader in Zend Framework. We will share this with you for your reference. The details are as follows:

Zend Framework provides Zend_Loader for dynamic file loading.

The specific usage and implementation are as follows:

1. Load files

Usage:

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

Specific implementation:

/** * 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;}

Parameter rules:

The implementation method has the following parameters:

The $ filename parameter specifies the file to be loaded. Note that $ filename does not need to specify any path, but only the file name. ZF checks the file security. $ Filename can only consist of letters, numbers, connectors-, underscores _ and periods ). The $ dirs parameter is not limited and can be used in Chinese.

The $ dirs parameter is used to specify the directory where the file is located. It can be a string or an array. If it is NULL, the program will go to the include_path of the system to find whether the file exists (include_path can be in php. set -- Haohappy note in ini). If it is a string or an array, it will go down to the specified directory and then find the include_path.

$ Once is of the boolean type. If it is TRUE, Zend_Loader: loadFile () uses the PHP function» include_once () to load the file. Otherwise, it is the PHP function» include (). (This parameter can only be true or false. The difference is the same as that between include () and include_once .)

2. Load class

Specific use:

Zend_Loader::loadClass('Container_Tree',  array(    '/home/production/mylib',    '/home/production/myapp'  ));

Specific implementation:

/*** 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 names will correspond to the php file in the corresponding directory according to the underline (as the directory separator) and add '. php'. For example, Container_Tree will point to Container \ Tree. php.
$ Dir can be an array or string. The directory is the path to remove the directory contained by the class name.

3. Determine whether a file is readable.

Specific use:

if (Zend_Loader::isReadable($filename)) {  // do something with $filename}

Specific implementation:

/** * 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;}

Specific parameters:

The $ filename parameter specifies the file name to be checked, including the path information. This method is encapsulated by the PHP function» is_readable (). is_readable () does not automatically search for files under include_path, while Zend: isReadable () does.

4. Autoloader

The Autoloader function of this class is no longer recommended. There are other Autoloaders, which will be described later.

5. Plug-in loader

The following is an example of how to use the help document:

Many Zend Framework components support plug-ins and allow the function to be dynamically loaded by specifying the class prefix and the path to the class file (which does not need to be in include_path or a file that does not need to follow the traditional naming conventions. Zend_Loader_PluginLoader provides common functions to complete this task.

The basic usage of PluginLoader follows the naming conventions of Zend Framework (a file is a class). when parsing a path, underline is used as the path separator. When deciding whether to load special plug-in classes, the optional class prefix can be passed for preprocessing. In addition, the path is searched in the LIFO order. Because of LIFO search and class prefix, namespace is allowed for the plug-in, so that the plug-in can be overwritten from the paths registered earlier.

Basic Use Cases

First, assume the following directory structure and class files, and the root (toplevel) directory and library directory are in 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

Now, create a plug-in loader to make various view assistant repositories available:

<?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');?>

Then, load a given view assistant by using the section after the prefix defined when the path is added to the class name:

<?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'?>

After the class is loaded, it can be instantiated.

Note: register multiple paths for a prefix

Sometimes, multiple paths use the same prefix. Zend_Loader_PluginLoader actually registers a path array for each given prefix. The last registration is checked first. When you use components in the incubator, this is quite useful.

Note: path defined during instantiation

You can provide the constructor with an optional "prefix/path" pair (or "prefix/multiple paths") array parameter:

<?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 can also allow shared plug-ins without using a single-State instance. This is accomplished through a static registry. During instantiation, the Registry name must be used as the second parameter of the constructor:

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

Other components that use the registry with the same name to instantiate PluginLoader can access the loaded paths and plug-ins.

Process Plug-In Path

The example in the previous section shows how to add paths to the plug-in loader, and how to determine the paths already loaded or delete them?

If $ prefix is not provided, getPaths ($ prefix = null) returns all paths with "prefix/path" pairs, or if $ prefix, getPaths ($ prefix = null) is provided) returns the path registered for the given prefix.

ClearPaths ($ prefix = null) clears all registered paths by default, or if $ prefix is provided and placed in the stack, only the paths associated with the given prefix are cleared.

RemovePrefixPath ($ prefix, $ path = null) allows you to selectively clear specific paths related to the given prefix. If $ path is not provided, all prefix-related paths are cleared. If $ path is provided and the corresponding prefix exists, only the related paths are cleared.
Test the plug-in and obtain the class name

Sometimes you want to determine whether the plug-in class has been loaded before executing an action. isLoaded () returns the status of the plug-in name.

Another common use case of PluginLoader is to determine the fully qualified plug-in Class Name of the loaded class. getClassName () provides this function. Generally, this is used together with isLoaded:

<?phpif ($loader->isLoaded('Adapter')) {  $class  = $loader->getClassName('Adapter');  $adapter = call_user_func(array($class, 'getInstance'));}?>

For more information about how to implement the plug-in loader, see Zend_Loader_PluginLoader and Zend_Loader. This is not an example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.