It’s quite possible that you still haven’t had the chance to read the preceding part of this series, where I went through the development of a simple file loader class with recursive search capabilities. Therefore, I listed the full source code corresponding to this class below, so you can quickly grasp how it works. Here it is:
class Loader { // constructor (not implemented) public function __construct(){}
// load recursively a specified file public static function load($file, $path) { $filepath = $path . '/' . $file; if (file_exists($filepath)) { require_once($filepath); } else { if (!is_dir($path)) { throw new Exception('The supplied path is invalid!.'); } if (FALSE !== ($handle = opendir($path))) { // search recursively the specified file while (FAlSE !== ($dir = readdir($handle))) { if (strpos($dir, '.') === FALSE) { $path .= '/' . $dir; self::load($file, $path); } } closedir($handle); } } throw new Exception('The specified file was not found!.'); } }
As you can see, the above “Loader” class bases all of its functionality on its static “load()” method, which is the one that recursively seeks the targeted file that needs to be dynamically included in the script. Now that you understand how this class does its thing, here’s an example that shows how to use it to include the pair of sample PHP files created at the beginning of the series. First, take a look at these files, please:
('sample_file1.php')
<?php echo ' This file has been loaded with the Loader class.' . '<br />'; ?>
('sample_file2.php')
<?php echo 'This file has been loaded at the following time: ' . date('H:i:s'); ?>
And now, pay attention to the following code sample, which shows the “Loader” class in action:
// example of usage of the recursive loader class // prepare path to search for the specified file $path = $_SERVER['DOCUMENT_ROOT'] . '/path'; // try to load the first specified file Loader::load('sample_file1.php', $path); // try to load the second specified file Loader::load('sample_file2.php', $path);
/* displays the following This file has been loaded with the Loader class. This file has been loaded at the following time 12:28:11 */ I don’t want to hurry you, but I’m sure that at this point you have a clear idea of the way that the previous file loader class uses its recursive capabilities for including certain files in a script. Therefore, the next step that I’m going to take will consist of building another loader application, which will make use of the “__autoload()” magic function. To learn more on how this brand new loading system will be created, click on the link below and read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|