Using the _autoload() Magic Function to Build Loader Appps in PHP

Welcome to the sixth part of an eight-part series that shows you how to build file loader applications in PHP. In this part I will discuss how to build a helpful file loading application by taking advantage of the nifty “__autoload()” magic function.

There are a number of tasks that PHP developers must tackle on a regular basis when building well-structured web applications. One of these is creating scripts that load a certain number of resources and dependencies required for those applications to work as expected.

While developing these file loading scripts can be as simple as using PHP includes for each requested file, there are specific situations when it’s necessary to create more complex loader programs that incorporate some additional features, such as automatic inclusion of dependencies, and recursive search of them across a given file system path as well. 

Developing an application like the one described above with PHP 5 isn’t as hard as it may seem at first glance, especially when taking advantage of the functionality provided by the Standard PHP Library (SPL) in conjunction with the “__autoload()” magic function. 

In the previous installments of this series I went through the process of creating a file loader class. This class was not only capable of seeking and including a targeted file by recursively traversing the directories and subdirectories of a supplied path, but it had the ability to perform this task without having to spawn any instances of the aforementioned class.  

How was this achieved? Well, by simply calling the class’s main loader method statically and nothing else. It was that easy, really. 

But, as I mentioned a few lines before, it’s also feasible (and desirable) to construct file loading applications by combining certain built-in features of PHP 5, such as its “__autoload()” magic function, among others. Therefore, in this sixth chapter of the series I’m going to explain how to build a brand new file loader mechanism that will rely on this PHP 5 function. 

Now, it’s time to leave all of the preliminaries behind us and start learning how to create a file loading system around the handy “__autoload()” function. Let’s begin right away!

{mospagebreak title=Review: building a file loader class the old way} 

It’s quite possible that you still haven’t had the chance to read the preceding part of this series, where I went through the development of a simple file loader class with recursive search capabilities. Therefore, I listed the full source code corresponding to this class below, so you can quickly grasp how it works. Here it is:

 

class Loader

{

// constructor (not implemented)

public function __construct(){}

 

// load recursively a specified file

public static function load($file, $path)

{

$filepath = $path . ‘/’ . $file;

if (file_exists($filepath))

{

require_once($filepath);

 }

else

{

if (!is_dir($path))

{

throw new Exception(‘The supplied path is invalid!.’);

}

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

{

// search recursively the specified file

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

{

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

{

$path .= ‘/’ . $dir;

self::load($file, $path);

}

}

closedir($handle);

}

}

throw new Exception(‘The specified file was not found!.’);

 }

}

 

As you can see, the above “Loader” class bases all of its functionality on its static “load()” method, which is the one that recursively seeks the targeted file that needs to be dynamically included in the script. 

Now that you understand how this class does its thing, here’s an example that shows how to use it to include the pair of sample PHP files created at the beginning of the series. First, take a look at these files, please:

 

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

?>

 

And now, pay attention to the following code sample, which shows the “Loader” class in action:

 

// example of usage of the recursive loader class

// prepare path to search for the specified file

$path = $_SERVER[‘DOCUMENT_ROOT’] . ‘/path’;

// try to load the first specified file

Loader::load(‘sample_file1.php’, $path);

// try to load the second specified file

Loader::load(‘sample_file2.php’, $path);

 

/* displays the following

This file has been loaded with the Loader class.

This file has been loaded at the following time 12:28:11

*/

I don’t want to hurry you, but I’m sure that at this point you have a clear idea of the way that the previous file loader class uses its recursive capabilities for including certain files in a script. Therefore, the next step that I’m going to take will consist of building another loader application, which will make use of the “__autoload()” magic function. 

To learn more on how this brand new loading system will be created, click on the link below and read the following section.

{mospagebreak title=Loading files with the autoload PHP magic function}  

Undeniably, one of the most useful features incorporated into PHP 5, aside from its solid object model, is the set of magic functions, which permit you to automatically load a determined file. 

As you may guess, in this particular case I’m talking about the “__autoload()” function. When this function is implemented, it allows you to build file loading scripts very quickly. 

To demonstrate a simple usage of this function, I’m going to define a sample class called “User,” which will store some data about a specific user: their first and last names, and their email address. 

Then, with that class available for testing purposes, I’m going to show how to include it in a script by directly using the “require_once()” function, and finally by means of the “__autoload()” function. 

That being explained, here’s how the “User” class looks:

 

class User

{

private $name = ‘Alejandro’;

private $email = ‘Gervasio’;

 

// constructor

public function __construct($name = ”, $email = ”)

{

if ($name != ”)

{

$this->name = $name;

}

 

if ($email != ”)

{

$this->email = $email;

 

}

}

 

// get user name

public function get_name()

{

return $this->name;

}

 

// get user’s email address

public function get_email()

{

return $this->email;

}

 

function __toString()

{

return ‘Name: ‘ . $this->name . ‘ Email: ‘ . $this->email;

}

}

 

So far, nothing spectacular is going on here, right? As you can see, the above “User” class has some simple setter and getter methods that permit you to set and retrieve the first and last names of a given user, as well as their email address. 

In addition, the “__toString()” magic method allows you to display the value of these properties very easily, but the rest of the class code is extremely easy to follow. 

So far, so good. Now that the previous “User” class has been properly defined, say that you need to use it within a simple program. In a typical case, to do this you’d use a script similar to the one below:

 

// loading the user class using require_once()

require_once ‘user.php’;

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Again, this example doesn’t bear any further discussion, because of its simplicity. However, see what happens when the “User” class is included via the “__autoload()” function:

 

// loading the user class using the __autoload() function

function __autoload($class)

{

$file = $class . ‘.php’;

if (file_exists($file))

{

require_once($file);

}

}

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Definitely, things have become much more interesting at this point. The class has now been included in the previous script by implementing the “__autoload()” function in a pretty basic way. Though small, this is certainly an improvement that leads toward loading files automatically.  

What’s more, it’s possible to make the “__autoload()” function throw an exception if the targeted file can’t be found. This feature has been implemented by the following script. Take a look at it, please:

 

// example on loading a class using the __autoload() function triggering an exception

 

// define a generic exception handler function

function exception_handler($e)

{

echo $e->getMessage();

}

 

set_exception_handler(‘exception_handler’);

 

function __autoload($class)

{

$file = $class . ‘.php’;

if(!file_exists($file)){

eval("class $class {}");

throw new Exception(‘Class ‘ . $class . ‘ not found.’);

}

require_once($file);

}

 

// create instance of User class

$user = new User();

// display user data

echo $user;

 

Well, admittedly the “eval()” function called when autoloading the “User” class isn’t the most elegant solution for triggering an exception, but it does a decent job when it comes to tying an error mechanism to the “__autoload()” function. 

However, it’s possible to polish the definition of this function a bit more by creating a more efficient exception handling script. Therefore, I’m going to finish this article by showing you how to develop such a script in a few easy steps. 

Now, please click on the link shown below and read the section to come.

{mospagebreak title=Implementing an enhanced exception mechanism} 

As I expressed in the section that you just read, a good epilogue for this tutorial will be demonstrating how to implement a better exception handling mechanism within the auto-loading script built earlier. So, bearing this concept in mind, below I developed a whole new code sample. It shows how to throw more insightful exceptions within the “__autoload()” function when the file to be included isn’t found. Here’s the example in question:

 

// define a generic exception handler function

function exception_handler($e)

{

echo $e->getMessage();

}

 

set_exception_handler(‘exception_handler’);

function __autoload($class)

{

$file = $class . ‘.php’;

if(!file_exists($file)){

return eval("class {$class}{public function __construct(){throw new Exception(‘Class {$class} not found!’);}}");

}

require_once($file);

}

 

// create instance of User class

$user = new User();

// display user data

echo $user;

As shown before, the implementation of the “__autoload()” function now allows you to throw an improved exception if the file that needs to be included by the calling script isn’t found. It’s short to code and read, indeed. 

And with this example, I’m completing this sixth chapter of the series on building file loading applications in PHP. As usual, feel free to tweak all of the code samples shown in this tutorial, so you can practice developing this kind of web-based program.  

Final thoughts  

That’s all for the moment. Over this sixth part of the series I discussed how to build a small –- yet helpful — file loading application in PHP 5 by taking advantage of the nifty “__autoload()” magic function, which made the whole development process a breeze. 

I have to say, though that I’m only scratching the surface when it comes to creating file loaders with PHP 5. The language provides yet another pair of powerful functions that are part of the Standard PHP Library, called “spl_autoload_register()” and “spl_autoload_register().” These functions can be used for building clever file loading applications very quickly.  

In the next article I’m going to explore these functions in depth, so now that you know what to expect from the upcoming tutorial, you won’t want to miss it! 

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

chat sex hikayeleri Ensest hikaye