Monday, March 16, 2009

Zend framework source code learning - Zend_Loader

include 'Zend/Loader.php';

The above two lines can save us from those long reqire_once list on top of php files. Let's have a look at the registerAutoload().

The method definition is public static function registerAutoload($class = 'Zend_Loader', $enabled = true). If we don't pass any parameters, the default class is Zend_Loader, and $enable is true, which allows the function to call spl_autoload_register.

if (!function_exists('spl_autoload_register')) {
require_once 'Zend/Exception.php';
throw new Zend_Exception('spl_autoload does not exist in this PHP installation');
It checks if spl_autoload_register function exists, because the magic autoload relies on this function.

loadClass() is the sole method of Zend_Loader. It looks through the path and directory, based on the $class name, and tries to load the class file. For example, if the $class is 'Zend_Log_Writer_Stream', it looks through 'Zend/Log/Writer/' and tries to load Stream.php file.

$methods = get_class_methods($class);
if (!in_array('autoload', (array) $methods)) {
require_once 'Zend/Exception.php';
throw new Zend_Exception("The class \"$class\" does not have an autoload() method");
spl_autoload_register(array($class, 'autoload'));
The codes check if the class possesses autoload method and tries to register the method.

Zend_Load defines and autoload method, which actually calls the loadClass().

So that is how Zend_Load works. If we call a class not defined, it automatically searchs the class file by its class name in include_path, and load the class file if it is found.

I havn't done the test by myself. But some articles on internet point out that Zend_Loader::registerAutoload() is bad in performance. It is quite possible, based on its code. So the developer must find a balance between speed and convenience.

No comments: