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!

{mospagebreak title=Review: a basic file loading system with PHP 5}

In case you still haven’t read the previous chapter of this series, where I went through the development of a pretty basic file loader class in PHP 5, I’ve included its full signature below, accompanied by an example of its usage, so you can understand how it works.

Please take a close look at the structure of the sample “Loader” class:

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!’);

}

require_once($filepath);

}

}

Indeed, the definition of the above “Loader()” class is so simple to understand that it doesn’t bear any further explanation. Therefore, let me show you another example aimed at illustrating how to use the class, this time for including a pair of PHP files that were created in the preceding article.

First, here are the aforementioned sample files, called “sample_file1.php” and “sample_file2.php” respectively:

(‘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 you’ve seen how the two trivial files listed above look, it’s time to code an example that shows how to use the previous “Loader” class to dynamically include these files. Here you have it:

<?php

 

try

{

// create instance of loader class

$loader = new Loader();

// load specified files

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

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

 

/* displays the following

This file has been loaded with the Loader class.

This file has been loaded at the following time: 2:27:15

*/

}

catch (Exception $e)

{

echo $e->getMessage();

exit();

}

?>

Definitely, from the code sample shown above, it’s extremely easy to grasp the logic that drives the “Loader()” class. Its core “load()” method behaves like an improved proxy for the “require_once()” PHP native function, plus the incorporation of a basic error handling mechanism, in this case implemented via the Exception class bundled with PHP 5.

So far, nothing spectacular is happening here, right? While the “Loader” class does decent work because it permits us to include several files by dynamically calling its “load()” method, it has a serious drawback. As I mentioned a moment ago, the “load()” method is invoked in the object context, which means that an instance of the “Loader” class has been previously created.

Is this really necessary? Not at all, believe me! And when I say this, I am only attempting to correctly apply the foundations of object-oriented programming. Since PHP permits us to statically call methods of a class, it’s feasible in this particular case to declare the “load()” method static and include the specified files without having to deal with unnecessary class instances.

Since it will be a considerable enhancement of the “Loader” class, in the next section I’m going to switch the default declaration of its “load()” to static, to avoid the issue discussed earlier.

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

{mospagebreak title=A static file loading method}

As I anticipated in the segment that you just read, one of the simplest ways to use the “Loader” class without having to create an instance of it consists of calling its “load()” method out of the object context, or in other words, statically.

PHP does support calling a non-static method statically (which is not supported when using static class properties), but to assure that the “load()” method will always be invoked statically, I’m going to refactor the class, this time declaring the method obviously static.

Does all of this jargon sound a bit confusing to you? Fear not. Only pay attention to the enhanced version of the “Loader” class, after implementing this subtle change. Here it is:

// define the loader class (the ‘load()’ method is declared static)

class Loader

{

// constructor (not implemented)

 public function __construct(){}

 

// load specified file

public static function load($filepath)

{

if (!file_exists($filepath))

{

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

}

require_once($filepath);

}

}

That was easy to code and read, wasn’t it? As you can see, now the “Loader” class looks nearly identical to its previous version, except for one small but crucial modification: its “load()” method has been declared static explicitly via the “static” keyword. This means that if the method is eventually called in the object scope (read dynamically), the PHP engine will complain loudly about this and throw an error.

Naturally, the most evident benefit in declaring this method static is that there’s no need to spawn an instance of the “Loader” class to call it. In this case, I’m getting the best of both worlds: I’m still able to include files using the “load()” method, but no object needs to be created.

However, the best way to understand the nitty-gritty of this process is by coding a concrete example. So, the last section of this tutorial will be dedicated to develop that example, so you can see how the improved version of the “Loader” class is really much more flexible and efficient.

Thus, don’t waste more time; read the following segment. It’s only one click away.

{mospagebreak title=Loading files using a static class method} 

To finish this second part of the series, I’m going to develop a short example to demonstrate how to include the pair of sample files shown previously by means of the “Loader()” class. In this case, of course, the “load()” method will be called statically.

Now that I have explained that, please pay close attention to the example, which looks like this:

<?php

try

{

// call ‘load()’ method statically and load specified files

Loader::load(‘sample_file1.php’);

Loader::load(‘sample_file2.php’);

 

/* displays the following

 This file has been loaded with the Loader class.

This file has been loaded at the following time 2:45:18

 */

}

catch (Exception $e)

{

echo $e->getMessage();

exit();

}

?>

As shown above, it’s perfectly possible to load as many files as required via the “Loader()” class, without needing to create an instance of it. Of course, this is a great improvement in the way that certain dependencies are included into a given PHP application, even when it’s necessary to make one static call per requested file.

But I’m only scratching the surface when it comes to building loading programs with PHP 5, so for the moment feel free to tweak all of the the code samples developed in this article and try to create a better loader class. The exercise will be really worthwhile.

Final thoughts

In this second part of the series, I explained (through various code samples) how to enhance the file loader class created in the first chapter simply by declaring its “load()” method static, and obviously by calling it statically as well, when including a specific file.

This is definitely a great breakthrough toward the development of an efficient file loading application, but there is still plenty of room for further enhancements. Therefore, in the upcoming article I’m going to extend the functionality of the loader class by providing it with the capacity for including files recursively.

Want to learn the full details of this process? Then don’t miss the next chapter!

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

chat sex hikayeleri Ensest hikaye