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!