To apply the lazy loading pattern within the script that you learned before, it's necessary to introduce a subtle change into the corresponding loader module. Basically, this modification will consist of registering the "load()" method of the "Loader" class with the "spl_autoload_register()" PHP function, so the method in question can be called automatically when a script attempts to include a class on demand. Having explained that, here's the enhanced definition of the loader module: // create custom FileNotFoundException exception class class FileNotFoundException extends Exception {}
// create custom ClassNotFoundException exception class class ClassNotFoundException extends Exception {}
spl_autoload_register(array('Loader','load'));
// define 'Loader' class class Loader {
public static function load($class) { if (class_exists($class, FALSE)) { return; } $file = $class . '.php'; if(!file_exists($file)) { throw new FileNotFoundException('File ' . $file . ' not found.'); } require $file; unset($file); if (!class_exists($class, FALSE)) { eval('class ' . $class . '{}'); throw new ClassNotFoundException('Class ' . $class . ' not found.'); } } } That was really simple to code and read, wasn't it? At this point, the loader module has suddenly turned into a true autoloader mechanism that will include a specified class on request, thanks to the use of the aforementioned "spl_autoload_register()" PHP function. Believe it or not, this small modification into the source code of the module permits to easily build scripts, or even entire applications, that include classes only when they are really required -- or in other words, that implement the lazy loading pattern. But if you're like me, you now want to see how the revamped version of the previous loader module can be put to work with the "User" class. Am I right? Great! In the last section of this article I'm going to create a basic script that will load that class in a lazy manner. To see how this script will be developed, go ahead and read the next section.
blog comments powered by Disqus |
|
|
|
|
|
|
|