Including Files Recursively with Loader Applications in PHP

Welcome to the fourth chapter of the series that shows you how to build loader applications with PHP. Made up of seven parts, this series uses a variety of code samples to teach you how to create modular programs. These programs are capable of recursively including files required by a given application, without having to explicitly call any “include()/include_once()” or “require()/require_once()” PHP function.

And now that you’ve been introduced to the main goal of this series, it’s time to summarize the topics that were discussed in the last tutorial. In the previous part I went through the development of a file loading class in PHP 5. This class was capable of searching recursively for a determined file on the web server, based on a starting path passed to its “load()” main method.

Having a class like this makes it much easier to dynamically load resources and dependencies that may be located in different folders on the server. Its recursive “load()” method does the hard work and takes care of the whole loading process, independently of the location of a required file. 

Nonetheless, the best way to understand how this loader class works and how functional it can be in concrete situations is by setting up several examples that show it in action. 

Bearing in mind this idea, in this fourth installment of the series I’m going to provide you with a number of code samples that will demonstrate the actual benefits of using the “Loader” class created in the preceding tutorial. 

Now, let’s leave the boring theory behind us and see the real functionality of this recursive file loader program. Let’s jump in!

{mospagebreak title=Review: the loader() class so far} 

Before I start creating some examples aimed at illustrating how to use the file loading class built in the last article of this series, let’s recall quickly how it was defined originally. 

So, as a reminder, here’s the full source that corresponds to that class. Pay close attention to it, please: 

<?php

// define a recursive loader class

class Loader

{

private $file = ”;

private $path = ”;

// constructor (not implemented)

public function __construct(){}

 

// set file to load

public function set_file($file)

{

$this->file = $file;

}

 

// get file to load

public function get_file()

{

return $this->file;

 }

 

// set path to load file

public function set_path($path)

{

$this->path = $path;

}

 

// get path to load file

public function get_path()

{

return $this->path;

}

// load recursively specified file

public function load($file, $path)

{

if (file_exists($file))

{

require_once($file);

return;

}

else

{

if (is_dir($path))

{

if (FALSE !== ($handle = opendir($path)))

{

// search recursively the specified file

while (FAlSE !== ($dir = readdir($handle)))

{

if (strpos($dir, ‘.’) === FALSE)

{

$path .= ‘/’ . $dir;

$file = $path . ‘/’ . $this->file;

$this->load($file, $path);

}

}

}

closedir($handle);

}

}

}

}

 

Undeniably, aside from the non-implemented constructor, the workhorse of the above “Loader” class is clearly its “load()” method. It actually takes care of loading a targeted file via the “require()” PHP function. Of course, the most important detail to stress here is the method’s recursive implementation, which permits us to seek the required file through folders and subfolders within the specified path. 

Now that you’re hopefully familiar again with the way that the “Loader()” class functions, it’s time to begin coding some examples that will demonstrate its functionality in concrete situations. 

With that premise in mind, in the following section I’m going to set up a fictional scenario in which the loading class will be used for including a sample file, regardless of its location within a selected directory on the web server. 

To learn the full details of how this brand new example will be developed, click on the link that appears below and keep reading.

{mospagebreak title=Recursively including PHP files} 

As I explained in the segment that you just read, the best way to understand how the previous “Loader()” class functions is by developing some concrete examples that show how to use it. So, since the class’s main task is to include required files dynamically, I’m going to use the two sample files created in preceding articles. They looked like this:

 

(‘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’);

?>

 

Now that there are two files available to be included by the loader class, it’s time to create a hypothetical scenario. Say the files in question are located on a directory called “folder1” on the web server (yes, my creativity really blows me away sometimes, especially when it comes to naming directories in a fancy way), which is one level below the location at which the loader class resides. 

Based on this simple directory hierarchy, it’s perfectly possible to code an example where the loader class includes the two previous files after performing a recursive search. The corresponding code sample would look as follows:

 

// create instance of Loader class

$loader = new Loader();

// set file to load

$loader->set_file(‘sample_file1.php’);

// set path of specified file

$loader->set_path($_SERVER['DOCUMENT_ROOT'] . ‘/folder1);

// try to load specified file

$loader->load($loader->get_file(), $loader->get_path());

// set another file to load

$loader->set_file(‘sample_file2.php’);

// try to load specified file

$loader->load($loader->get_file(), $loader->get_path());

 

/* displays the following

This file has been loaded with the Loader class.

This file has been loaded at the following time 20:33:25

*/

 

From the example shown above, it’s clear to see how the loader class really works. In this specific case, the starting path we use to look for a required file is simply the aforementioned “folder1” directory, which is located one level below the web server’s root — but naturally the path can be easily modified and make the class seek for other locations. 

Once the appropriate path has been set, the pertinent “load()” method is called dynamically to include  the “sample_file1.php” file, and then the remaining one, called “sample_file2.php.” This demonstrates the actual functionality of the “Loader” class when it comes to including specified files using a recursive search. 

While the previous example should be illustrative enough to show how the loader class does its thing, I’d like to finish this tutorial by creating a final code sample that demonstrates the capability of the class when the targeted files to be included are located two levels below the web server’s root. 

This wrapping example will be developed in the last segment of the article. Please click on the link that appears below and read the next few lines. We’re almost finished!

{mospagebreak title=Changing the location of required files}  

I’d like to end this fourth part of the series by showing you one last example that illustrates how the loader class can be capable of including the same sample files that you saw in the previous section — but this time, these files are placed under a directory that’s located two levels below the web server’s root. 

To demonstrate the recursive search abilities of the class in a case like this, below I included another code sample, where the files to be included now reside in a fictional new folder called “folder2.” Study the following example closely to grasp how it works:

 

// create instance of Loader class

$loader = new Loader();

// set file to load

$loader->set_file(‘sample_file1.php’);

// set path of specified file

$loader->set_path($_SERVER['DOCUMENT_ROOT']);

// try to load specified file

$loader->load($loader->get_file(), $loader->get_path());

// set another file to load

$loader->set_file(‘sample_file2.php’);

// try to load specified file

$loader->load($loader->get_file(), $loader->get_path());

 

/* displays the following

This file has been loaded with the Loader class.

This file has been loaded at the following time 22:21:09

*/

 

As you can see above, even when the sample files to be included now are located in a directory that’s two levels below the root of the web server, the loader class will load them successfully regardless of their location, thanks to the recursive method it employs to perform the inclusion process. 

Also, you may want to create your own examples with the loader class. Try putting your required files at different locations on the file system, and see how the class does a recursive search with the new supplied path. This exercise will be helpful for sharpening your skills in building loading programs with PHP 5. 

Final thoughts 

Over the course of this fourth article of the series, I proceeded to create some basic examples that hopefully demonstrated the actual functionality of the file loader class that you saw previously. 

As you saw in the examples, the class was capable of including a specific file or resource in a recursive way, as long as the file in question was located at the same level and below of the starting search path. This makes it a flexible and effective loading mechanism. 

In the article to come, I’m going to discuss how to take advantage of the functionality provided by the loader class, but without having to create an instance of it. 

Don’t miss the next part!

[gp-comments width="770" linklove="off" ]

chat