The loader and pluginloader usages in the Zend Framework are analyzed in this paper. Share to everyone for your reference, specific as follows:
The Zend framework provides zend_loader for dynamically loading files.
The following are specific uses, as well as specific implementations:
1. Loading files
How to use:
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 is the complete filename, including any * extension such as ". php". Note This a security check is performed this * does not permit extended characters in the filename.
This are * intended for loading Zend Framework files. * If $dirs is a string or a array, it'll search the directories * in the order supplied, and attempt to load the fi
RST matching file. * * If the file is not found in the $dirs, or if no $dirs were specified, * It'll attempt to load it from PHP inclu
De_path.
* * If $once is TRUE, it would use include_once () instead of include (). * * @param string $filename * @param string|array $dirs-optional either a path or array of paths * to S
Earch. * @param boolean $once * @return Boolean * @throws zend_exception */public static function LoadFile ($filename, $dir
s = null, $once = False) {Self::_securitycheck ($filename); /** * SEarch in provided directories, as AS and include_path */$incPath = false; if (!empty ($dirs) && (Is_array ($dirs) | | is_string ($dirs)) {if (Is_array ($dirs)) {$dirs = implode (PAT
H_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:
As an implementation method, there are the following parameters
$filename parameter specifies the file you want to load, note that $filename does not need to specify any paths, just the file name. The ZF will conduct security checks on the files. $filename can only be by letters, numbers, connectors-, underscores _ and English. Composition (half angle). $dirs parameters are not limited, you can use the Chinese and so on.
$dirs parameter is used to specify the directory in which the file is located, either a string or an array. If NULL, the program will go to the system's include_path to find out if the file exists (Include_path can set the--haohappy note in php.ini), if it is a string or an array, go down to the specified directory and then the Include_ Path
The $once parameter is a Boolean type, or PHP function»include () If the PHP function»include_once () is used to load the file for True,zend_loader::loadfile (). (This argument can only be true or false, and the difference is the same as that of 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 PHP file.
The filename must be formatted * as "$class. php". * If $dirs is a string or a array, it'll search the directories * in the order supplied, and attempt to load the Firs
T matching file. * * If $dirs is null, it would split the class name at underscores to * generate a path hierarchy (e.g., "Zend_example_clas
S "would map * to" zend/example/class.php "). * * If the file is not found in the $dirs, or if no $dirs were specified, * It'll 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 being a string or an array '); }//Autodiscover the path from the class name//implementation are PHP Namespace-aware, and based on//Frame Work 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.P
HP ';
throw new Zend_exception ("File \" $file \ "does not exist or class \" $class \ "is not found in the file);
}
}
The $class class name will correspond to the PHP file in the corresponding directory based on the underscore (as a directory divider), plus '. php ', for example, Container_tree will point to container\\tree.php.
$dir can be an array or a string. A directory is a path that removes the directory contained by the class name.
3. Determine if 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. * * ZF-2900: * If You use custom error handler, please check whether return value * to error_reporting () is
zero or not.
* At Mark of fopen () can isn't suppress warning if the handler is used. * * @param string $filename * @return Boolean/public static function IsReadable ($filename) {if is_readable ($fil
ename)) {//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 WI
Ndows, and path provided is clearly a 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 name of the file to check, including path information. This method encapsulates the PHP function»is_readable (), is_readable () does not automatically find files under Include_path, and zend::isreadable () can.
4.Autoloader
The autoloader feature of this class is deprecated, so it is no longer described. There are other autoloader, later specific instructions.
5. Plug-in Loader
The specific examples given in the Help article are as follows, which can be used for reference:
Many Zend Framework components support plug-ins that allow you to dynamically load functions by specifying the prefix of the class and the path to the class (without needing to follow a file in Include_path or without following a traditional naming convention). Zend_loader_pluginloader provides an ordinary function to do this work.
The basic usage of Pluginloader follows the naming convention of the Zend Framework (a file Class), which uses an underscore as the path separator when parsing the path. When deciding whether to load a particular plug-in class, allow the optional class prefix to be passed to preprocess. In addition, the paths are searched in LIFO order. Because of the LIFO search and the prefix of the class, namespaces are allowed to be given to plug-ins so that they can be overwritten from earlier registered paths.
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 a variety of view assistant warehouses 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 ');
? >
A given view assistant is then loaded with the following part of 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 '
?>
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 an array of paths for each given prefix, and the last registered is checked first, which is quite useful when you use the components in the incubator.
Note: Defining paths when instantiating
You can provide the constructor with an optional prefix/path pair (or "prefix/multiple Paths") array parameters:
<?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 optionally allows shared plug-ins without using a singleton instance, which is done through the static registry and requires the registry name as the second parameter of the constructor when instantiated:
<?php
//Store plugins in static registry ' Foobar ':
$loader = new Zend_loader_pluginloader (Array (), ' Foobar ' );
? >
Other components that instantiate Pluginloader using the registry with the same name will have access to the paths and plug-ins that have already been loaded.
Handling Plug-in paths
The example in the previous section how to add a path to the plug-in loader, how to determine which path has been loaded or delete them?
If $prefix is not provided, getpaths ($prefix = null) returns all paths with a prefix/path pair, or if $prefix is provided, getpaths ($prefix = null) returns the path registered for the given prefix.
Clearpaths ($prefix = null) clears all registered paths by default, or if $prefix is provided and placed on the stack, only those paths associated with the given prefix are cleared.
Removeprefixpath ($prefix, $path = NULL) allows selectively purging of specific paths associated with a given prefix. If $path is not provided, all and prefix-related paths are cleared, and if a $path is provided and the corresponding prefix exists, only the associated path is cleared.
Test the plug-in and get the name of the class
Sometimes you want to determine whether the plug-in class has already been loaded before executing an action, and isLoaded () returns the state of the plug-in name.
Another common use case for Pluginloader is to determine the fully qualified plug-in class name of the loaded class, GetClassName () to provide that functionality. Generally, this is used in conjunction with isLoaded ():
<?php
if ($loader->isloaded (' Adapter ')) {
$class = $loader->getclassname (' Adapter ');
$adapter = Call_user_func (Array ($class, ' getinstance '));
>
The implementation of the specific plug-in loader can refer to Zend_loader_pluginloader and Zend_loader. This is not a tiring statement.
More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"
I hope this article will help you with the PHP program design.