As you'll possibly recall, the "autoload()" method that belongs to the previous loader class performs the recursive search of a particular class via another method, not surprisingly called "recursive_autoload()." As I mentioned earlier, though, it's feasible to simplify this process by means of the RecursiveDirectoryIterator class that comes with the SPL library. To demonstrate how this can be accomplished, below I included an improved version of the "Autoloader" class, this time using the directory iterator class. Here's how the class now looks: spl_autoload_register(NULL, FALSE); spl_autoload_extensions('.php'); spl_autoload_register(array('Autoloader', 'autoload'));
// define Autoloader class class Autoloader { // constructor not implemented public function __construct(){}
// autoload recursively a specified class public static function autoload($class) { // Set path for specified file $class = strtolower($class) . '.php'; // try to include recursively the class file $rit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(BASEPATH)); foreach ($rit as $entry) { if ($class === $entry->getFileName()) { require_once($entry->getPathname()); return; } } throw new FileNotFoundException('File ' . $class . ' not found!'); } }
// define custom FileNotFoundException exception class class FileNotFoundException extends Exception { public function __construct($message) { parent:: __construct(); die($message); } } Definitely, things are getting much more interesting now. As you can see, the "autoload()" method defined above uses the functionality of the RecursiveDirectoryIterator native class to recursively search for a specified class through the file system. If the class in question is found, then it's included via a simple "require_once()" function. Otherwise, a custom "FileNotFoundException" exception is thrown and caught appropriately. Not too difficult to grasp, right? From the code sample shown previously, it's obvious to see how useful the Standard PHP library can be for loading classes automatically and performing recursive searches. However, the best way to understand how the enhanced version of the "Autoloader" class works is by means of an illustrative example. Therefore, in the last section of this article, I'm going to develop that example, in this case for loading the "User" class defined before. Now, jump forward and read the next few lines. We're almost done!
blog comments powered by Disqus |
|
|
|
|
|
|
|