HomePHP Using Static Methods to Build Loader Apps in PHP
Using Static Methods to Build Loader Apps in PHP
If you’re a PHP developer who has already worked with popular third-party frameworks like Kohana and CodeIgniter, or even better, have created one all by yourself, then you're familiar with building file loading applications. The process can be tackled pretty easily, either by using a procedural approach or the object-oriented paradigm. In this eight-part series, we take a close look at building file-loading applications. This second part of the series will focus on static methods.
As its name suggests, a file loading program (or a resource loading program, to express the concept more accurately), is simply a PHP module that takes care of including, usually via its set of “include()/require() native functions, files that are required by an application to make it work as expected.
In many cases, loading files within a program can be seen simply as a one-to-one relationship, where one “include()/include_once() or “require()/require_once()” function is used explicitly with each required file. Although this method can be quite effective when developing small-scale applications, it can lead to many maintenance headaches when building larger ones.
Fortunately, it’s possible to create more sophisticated and elegant file loaders with minor hassles, by combining classic PHP includes along with the magic “__autoload()” function and some of the functions and classes supplied by the Standard PHP Library (SPL) available in PHP 5.
The goal of this series of articles is to demonstrate, in a step-by-step fashion, how to build several file loading programs. These range from using a “require_once()” function per requested file, to developing loader classes capable of including a specified file by using a recursive search through the file system on a web server.
Actually, I’m getting ahead of myself, since it’s time to summarize the topics that were covered in the first part of this series. In that article, I explained how to create a rudimentary file loader class, which via a dynamic “load()” method, had the ability to include a specific file into a given application.
It’s worthwhile to mention, however, that it was necessary to create an instance of the aforementioned class to load a determined file. This is a process that can be completely avoided in terms of good coding habits. But how can this be achieved? Well, it’s feasible to statically call the class’s load()” method, preventing its unwanted instantiation.
So, in the next few lines I’m going to illustrate how to do that, by way of a decent variety of code samples that you’ll grasp very quickly.
Are you ready to tackle this second installment of the series? Then let’s move forward now!