Building Loader Apps in PHP

Loading sources on the fly is one of the most common tasks that PHP programmers have to tackle during the development of web applications. This typical situation must be faced independently of the scale of the programs being created. This means a loader mechanism must be developed. Keep reading as we take a close look at these mechanisms in this eight-part article series.

Ranging from loading configuration and generic data files, to including classes when using an object-oriented approach, one thing is certain: sooner or later, some kind of effective loader mechanism must be implemented to gather the dependencies required for a particular application.

Of course, when I mention the term “loader,” you might be thinking that the simplest version of a mechanism like this would be the set of “include/require/” native functions provided by PHP, in all its flavors. And you’d be right; in many cases these functions are the quickest way to include files within a program, according to its specific needs.

While it’s true that it’s impossible to build modular applications without using includes, it’s also valid to point out that in the older days of PHP 4, these functions had to be called explicitly. Fortunately, with the release of PHP 5 a long time ago, there is no longer any need to invoke them directly, thanks to the incorporation of the handy “__autoload()” magic function.

Besides, as you may know, PHP 5 comes packaged with the Standard PHP Library (SPL), which includes, among the bunch of powerful classes and interfaces with which it’s armed, two popular functions, called “spl_autoload()” and “spl_autoload_register().” They permit, in the first case, the use of the default implementation for the aforementioned “__autoload()” function and, in the last case, registration of a callback function for loading files.

With all of these helpful resources freely at your disposal, it’s pretty easy to build full-featured “loader” applications with PHP 5. So, assuming that you’re interested in this topic, in this series of articles I’m going to develop some sample loading applications. I will start with some basic examples, and progressively  add more complexity to them, such as including recursive file loading capabilities.

Now that you’ve been introduced to the subject of this article series, it’s time to start learning how to build “loader” programs in PHP 5. Let’s get started!

{mospagebreak title=Start building loading programs with a require_once() function}

As I said at the beginning, the simplest version of a loading application can be built by explicitly calling some “include()/require()” functions, which are used per file requested. So, to recreate a typical scenario in which these functions are utilized, suppose for a moment that there are two basic files that need to be included within an application, that are defined as follows:




echo ‘This file has been loaded with the require_once() function.’ . ‘<br />’;






echo ‘This file has been also loaded with the require_once() function.’ . ‘<br />’;


As shown previously, the two sample files listed above are extremely simple to grasp, so I’m not going to waste your time explaining how they work. Nonetheless, since there’s a fictional application that needs to include the files to do its business, a typical loader file would look like this:

(‘loader.php’ file)


// include first sample file via a require_once() function



// include second sample file via a require_once() function


Definitely, the definition of the “loader.php” file is very basic, but it does show in a nutshell a classic situation, where one “require()” function is called per requested file. In addition, the following output would be produced by the loader file:

This file has been loaded with the require_once() function.

This file has been also loaded with the require_once() function.

This would be quite possibly the most basic implementation of a file loading mechanism in PHP. Despite its simplicity, it works pretty well when building small-scale applications.

However, when it comes to developing larger PHP programs, things can get more complex. There will probably be multiple files using many includes. This situation can lead to dealing with tedious debugging and maintenance issues.

So, to prevent the vast majority of these eventual problems, it’s necessary to create a file loading system that works in a more modular way, and at the same time allows us to abstract the whole loading process a bit further.

This objective can be achieved quite decently by using a simple loader class. Therefore, in the course of the section to come I’m going to discuss how to build such a class in a few basic steps.

To learn more about how this procedure will be accomplished, click on the link that appears below and keep reading.

{mospagebreak title=Building a basic file loader class}

As I stated previously, developing a file loading system that abstracts the load process a bit further is a straightforward procedure that can be tackled with minimal efforts. Basically, this system will base its functionality on a simple loader class that will behave as a proxy for a “require_once()” function. 

Imagine now that there are a couple of files that need to be included by a certain PHP application, whose definitions are as follows:




echo ‘ This file has been loaded with the Loader class.’ . ‘<br />’;






echo ‘This file has been loaded at the following time: ‘ . date(‘H:i:s’);


Again, it’s fair to say that I’m not going to waste your time (and mine) discussing how the above files do their things. Instead, pay close attention to the signature of the file loading class below, which not surprisingly has been called “Loader().” It looks like this:

class Loader


// constructor (not implemented)

public function __construct(){}


// load specified file

public function load($filepath)


if (!file_exists($filepath) OR is_dir($filepath))


throw new Exception(‘The specified file cannot be found!’);





Despite its rather basic definition, the previous “Loader()” class is a considerable breakthrough when it comes to building a file loading mechanism. It not only acts like a wrapper for the “require_once()” function, but it handles the eventual errors that might occur during the load process in a more elegant way, through native PHP exceptions.

At this point, everything is starting to look a bit better. I created a basic loader class, and there are a couple of sample files that need to be included within a fictional application to display some trivial messages on screen.

The question that comes up now is: how can these two files be loaded by the previous “Loader” class? Well, it’s quite possible that you’ve already found the answer, but in the last section of this tutorial I’m going to create a hands-on example that will demonstrate how to use this class in a few simple steps.

To learn more about how this example will be developed, go ahead and read the next segment.

{mospagebreak title=The loader class in action} 

Definitely, a good epilogue for this first chapter of the series will be demonstrating how the file loading class that you saw in the previous section can be put to work. With that premise in mind, below I included a short code sample that shows how to include the two sample files created earlier by using the loaded class. Here it is:





// create instance of loader class

$loader = new Loader();

// load specified files




/* displays the following

This file has been loaded with the Loader class.

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



catch (Exception $e)


echo $e->getMessage();




Well, as you can see in the above example, the two basic files defined previously have been successfully included by the “Loader” class via its pertinent “load()” method. In this particular case, it’s been assumed that both the class and the files being loaded reside under the same directory on the web server, but naturally it’s possible to specify the full paths of these files, if they’re incidentally located on a different folder.

And with this last example, I’m finishing this introduction to building loader applications with PHP 5. This first part is pretty simple to digest, at least for experienced developers, but this is only the beginning.

In the interim, feel free to edit all of the code samples included in this tutorial, and try to create your own file loader class. The experience will be truly educational.

Final thoughts

Over this first episode of the series, I explained how to construct a couple of basic file loading systems. The first mechanism used a procedural approach, while the last one relied on a class to load a specified file.

However, I’d like to point out one important thing with reference to the way that the loader class was built. As you’ll recall, its “load()” method was called in an object context (in other words, dynamically), in order to include a specific file. This means that an instance of this class needed to be created — something which can be easily avoided.

But how can we do this? Well, by simply calling the mentioned method statically, it’s possible to avoid the unnecessary instantiation of the loader class. But the full details of this process will be discussed in the next article, so now that you’ve been told, you simply can’t miss it!

Google+ Comments

Google+ Comments