Eliminate require_once with Zend_Loader::registerAutoload();

This is a quick post on how to use the Zend Framework Zend_Loader component, and namely the bundled autoloader, to eliminate the need for require_once() statements in your PHP class files. Just place something like the following code somewhere in your bootstrap file (or main index, or any other file executed early in the cycle of every request):
set_include_path(
'.' . PATH_SEPARATOR .
'../../private/library' . PATH_SEPARATOR .
'../../private' . PATH_SEPARATOR .
'../../private/library/Util' . PATH_SEPARATOR .
'../../private/services' . PATH_SEPARATOR .
'../../private/services/helpers' . PATH_SEPARATOR .
get_include_path()
);

require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
The Zend autoloader works on the convention that any referenced class will reside in one of the directories in your class-path and will be contained in a file of the same name plus a .php extension. That is, if your code is referencing a class called FooBar, the Zend loader will look for FooBar.php in all the include path folders.

One thing to note is that as far as I know (and I may be mistaken) the autoloader is not recursive, meaning you need to add every top-level directory containing class files to your include path as above.

It's also possible to create your own autoloader class and register it with the Zend_Loader. In this you could put whatever logic you wanted to find your classes. I haven't tried this yet but from the Zend manual, it would look something like this:
class My_Loader extends Zend_Loader
{
public static function loadClass($class, $dirs = null)
{
parent::loadClass($class, $dirs);
}

public static function autoload($class)
{
try {
self::loadClass($class);
return $class;
} catch (Exception $e) {
return false;
}
}
}

Zend_Loader::registerAutoload('My_Loader');
All you have to do is change the logic of the loadClass() function above to find and load the file containing the $class name. I suspect making this recursive could lead to performance issues however, especially if you have large libraries in your include path so I'd be careful about doing that.

Comments

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word