Automatically load in ZendFramework

Source: Internet
Author: User
Tags autoloader spl
Automatic loading is a mechanism that allows you to manually set dependent files in your PHP code. Every? ThePHP automatic loading manual emphasizes that once the automatic loader is set

Introduction
Automatic loading is a mechanism that allows you to manually set dependent files in your PHP code. Every? The PHP automatic loading manual emphasizes that once the automatic loader is defined, it will be automatically called when you try to use a class or interface that is not yet defined"
With automatic loading, you don't have to worry about where a class is in your project. With well-defined automatic loading, you do not need to worry about the location of a class file relative to the current class file. if you simply use this class, the automatic loader will execute the file search task.
In addition, automatic loading is because it does not load until the last moment and is sure that the match only appears once. this is a huge performance improvement-especially if you spend time clearing require_once () before deploying it () when calling
ZendFramework encourages automatic loading and provides many tools to automatically load library and application code. This tutorial covers these tools and shows you how to use them efficiently.
Objectives and design
Class naming conventions
To understand automatic loading in ZendFramework, you must first understand the relationship between class names and class files.
ZendFramework draws on the idea from PEAR that the class name and file system have a relationship. To solve the file path, replace the underscore (_) with a directory separator and add the suffix ". php ". For example, "Foo_Bar_Baz" corresponds to "Foo/Bar/Baz. php" in the file system ". This class can also be solved by setting the include_path in PHP. it allows include () and require () to search for file names through relative paths in include_path.
In addition, for every PEAR and PHP project, we recommend that you use the vendor or project prefix for your code. This means that all the classes you write will share the same class prefix. for example, all the code in ZendFramework has the "Zend _" prefix. This naming convention helps prevent name conflicts. In ZendFramework, we often call it the "namespace" prefix. be careful not to confuse it with the PHP local namespace (be careful not toconfuse it with PHP's native namespace implementation ).
ZendFramework follows these simple rules internally. Our code standards encourage you to do this, just like for all the library code.
Protocols and design for automatic loaders
Zend_Loader_Autoloader provides automatic loading support for Zend Framework. it has the following objectives and design elements:
· Provides namespace matching. If the prefix of a class namespace is not in the registered namespace list, FALSE is returned immediately. In this way, we can make a optimistic match, just as we will return to other auto loaders (Thisallows for more optimistic matching, as well as fallback to otherautoloaders .)
· The Auto-loader can be used as a backup auto-loader. When a team may be widely distributed or uses an unknown namespace prefix setting, the automatic loader should still be set so that it tries to match any namespace prefix. Note that this method is not recommended because it will lead to unnecessary search
· Enable error suppression. We feel that the same is true for the great PHP community-error suppression is a bad idea. It is expensive and covers very real application problems. Therefore, it should be off by default. However, if developers insist on opening it, we can do the same.
· Allows custom callback to be automatically loaded. Some developers do not want to use Zend_Loader: loadClass () for automatic loading, but still want to use the ZendFramework mechanism. Zend_Loader_Autoloader allows you to specify a candidate callback for automatic loading.
· Allows the SPL to automatically load the chain. The purpose of this operation is to allow another auto-loader to be specified. for example, the class resource loader does not have a ing relationship with the file system-it is registered before or after the main ZendFramework automatic loader
Auto-loader usage
Now that we know what automatic loading is, and understand the goal and design of the Framework automatic loading solution. Let's see how to use Zend_Loader_Autoloader.
In the simplest case, you only need to require the class and then instantiate it, because Zend_Loader_Autoloader is a singleton) (because the SPL auto-loader is a single resource), we use getInstance () to get an instance.
Require_once 'zend/Loader/Autoloader. php ';
Zend_Loader_Autoloader: getInstance ();
By default, this will allow you to load any class namespace prefix with "Zend _" or "ZendX _", as long as they are in your include_path
What happens if you have another namespace prefix to use? The best and simplest method is to call the registerNamespace () method on the instance.
Require_once 'zend/Loader/Autoloader. php ';
$ Loader = Zend_Loader_Autoloader: getInstance ();
$ Loader-> registerNamespace ('foo _');
$ Loader-> registerNamespace (array ('foo _ ', 'Bar _'));
Alternatively, you can tell Zend_Loader_Autoloader to act as a "back-up (fallback)" automatic loader. This means that it will process any class regardless of the namespace prefix.
$ Loader-> setFallbackAutoloader (true );
Warning
Do not use the fallback automatic loader.
We do not recommend this when trying to use Zend_Loader_Autoloader as the backup auto-loader.
Internally, Zend_Loader_Autoloader uses Zend_Loader: loadClass () to import classes. That method uses include () to try to import a given class file. if it fails to include (), a Boolean value of FALSE is returned and a PHP warning is published. The latter may actually cause some problems:
If display_errors is enabled, the warning is included in the output.
The error_reporting level you have selected may also confuse your logs.
You can suppress the error message (this is detailed in the Zend_Loader_Autoloader document). However, when display_errors is enabled, the suppression is only related. the error log will always display messages. For these reasons, we recommend that you always set the namespace prefix that can be recognized by the automatic loader.
Note: namespace prefix vs PHP namespace
At the time of writing this tutorial, PHP5.3 has been released. in this version, PHP now officially supports namespaces.
However, Zend Framework is created earlier than PHP5.3 on a date, and the same applies to namespaces. In ZendFramework, we refer to the "namespace" as the namespace in practice, that is, the class with the prefix of the "namespace" of the vendor (vendor. For example, all ZendFramework class names are prefixed with "Zend _"-that is, our vendor (vendor) "namespace"
ZendFramework plans to provide local PHP namespace support in auto-loaders in future versions. In addition, its own library will use namespaces in Version 2.0.0.
If you have an automatic loader that you want to use Zend Frameworkd to customize -- you may also use an automatic loader in a third-party library -- you can use pushAutoloader () and unshiftAutoloader () of Zend_Loader_Autoloader () method. These methods add the auto-loader to an internal auto-loading chain called the pre-execution Zend Framework (These methodswill append or prepend, respectively, autoloaders to a chain thatis called prior to executing Zend Framework's internal autoloadingmechanic ). This method has the following advantages:
Each method accepts the optional second parameter: class namespace prefix. This can be used to indicate that a given auto-loader should be used only when looking for a class with the specified class prefix. If the class to be processed does not have that prefix, the auto-loader will be skipped-this will lead to performance improvement
If you need to operate the spl_autoload () registry, any automatic loader that points to the callback of the instance method may cause problems (any autoloadersthat are callbacks pointing to instance methods can poseissues ), because spl_autoload_functions () does not return the same exact callback. Zend_Loader_Autoloader has no such restrictions.
The automatic loader that manages this method can make any valid PHP callback (Autoloaders managed this way may be anyvalid PHP callback ).
// Append function 'My _ autoloader 'to the stack,
// To manage classes with the prefix 'My _':
$ Loader-> pushAutoloader ('My _ autoloader ', 'My _');

// Prepend static method Foo_Loader: autoload () to the stack,
// To manage classes with the prefix 'foo _':
$ Loader-> unshiftAutoloader (array ('foo _ Loader ', 'autoload'), 'foo _');
Automatic resource loading
If you fully read the design objectives of autoloader, the last point in that section indicates that the solution should include this situation. ZendFramework uses Zend_Loader_Autoloader_Resource to do these tasks.
A resource is only the name and path of a corresponding component namespace (after it is added to the namespace of the automatic loader) (relative to the base path of the automatic loader ). In the action, we will do the following:
$ Loader = new Zend_Application_Module_Autoloader (array (
'Namespace' => 'blog ',
'Basepath' => APPLICATION_PATH. '/modules/blog ',
));
Once you have a loader in a proper location, you need to notify it (you then need to inform it ofthe varous resource types it's awareof) of many resource types it knows ). These resource types are simple subtrees and prefixes.

For example, consider the following tree
Path/to/some/resources/
|-Forms/
| '-Guestbook. php // Foo_Form_Guestbook
|-Models/
|-DbTable/
| '-Guestbook. php // Foo_Model_DbTable_Guestbook
|-Guestbook. php // Foo_Model_Guestbook
| '-GuestbookMapper. php // Foo_Model_GuestbookMapper
The first step is to create a resource loader:
$ Loader = new Zend_Loader_Autoloader_Resource (array (
'Basepath' => 'path/to/some/resources /',
'Namespace' => 'foo ',
));
Next, we need to define some resource types.
Zend_Loader_Autoloader_Resourse: addResourceType () has three parameters: Resource "type" (any string), Path of the base path may exist, and component prefix used for the resource type. In the preceding tree, we have three resource types: Form (with a component prefix "Form" in the "forms" subdirectory), model (in the "models" subdirectory, with a component prefix "Model") and dbtable (in the "models/DbTable" subdirectory, with the "Model_DbTable" component prefix ). We define them as follows:
$ Loader-> addResourceType ('form', 'Form', 'form ')
-> AddResourceType ('model', 'models', 'model ')
-> AddResourceType ('dbtable', 'Models/dbtable', 'Model _ dbtable ');
Once defined, we can simply use the following class
$ Form = new Foo_Form_Guestbook ();
$ Guestbook = new Foo_Model_Guestbook ();
Note: automatic loading of module resources
The MVC layer of ZendFramework encourages the use of "modules", which are self-contained applications on your site. By default, the module has many typical resource classes. ZendFramework even recommends a standard directory layout for the module. The automatic resource loader is so useful in this example-so useful that when you create a bootstrap class (bootstrapclass) that extends to Zend_Application_Module_Bootstrap for your module (module, they are enabled by default. For more information, see Zend_Loader_Autoloader_Module.
Conclusion
ZendFramework encourages autoloading, and even initializes it by default in Zend_Application. We hope this tutorial will provide you with the Zend_Loader_Autoloader information you need to use and extend its functions by attaching a custom auto-loader or resource auto-loader.

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.