Basic Autoloader UsageNow that we have an understanding of what autoloading is and the goals and design of Zend Framework's autoloading solution, let's look at how to use Zend_Loader_Autoloader. In the simplest case, you would simply require the class, and then instantiate it. Since Zend_Loader_Autoloader is a singleton (due to the fact that the SPL autoloader is a single resource), we use getInstance() to retrieve an instance.
By default, this will allow loading any classes with the class namespace prefixes of "Zend_" or "ZendX_", as long as they are on your include_path. What happens if you have other namespace prefixes you wish to use? The best, and simplest, way is to call the registerNamespace() method on the instance. You can pass a single namespace prefix, or an array of them:
Alternately, you can tell Zend_Loader_Autoloader to act as a "fallback" autoloader. This means that it will try to resolve any class regardless of namespace prefix.
Warning
Do not use as a fallback autoloaderWhile it's tempting to use Zend_Loader_Autoloader as a fallback autoloader, we do not recommend the practice. Internally, Zend_Loader_Autoloader uses Zend_Loader::loadClass() to load classes. That method uses include() to attempt to load the given class file. include() will return a boolean FALSE if not successful -- but also issues a PHP warning. This latter fact can lead to some issues:
You can suppress the error messages (the Zend_Loader_Autoloader documentation details this), but note that the suppression is only relevant when display_errors is enabled; the error log will always display the messages. For these reasons, we recommend always configuring the namespace prefixes the autoloader should be aware of
If you have a custom autoloader you wish to use with Zend Framework -- perhaps an autoloader from a third-party library you are also using -- you can manage it with Zend_Loader_Autoloader's pushAutoloader() and unshiftAutoloader() methods. These methods will append or prepend, respectively, autoloaders to a chain that is called prior to executing Zend Framework's internal autoloading mechanism. This approach offers the following benefits:
Autoloaders managed this way may be any valid PHP callback.
|