Using the spl_autoload() Functions to Build Loader Apps in PHP

Welcome to the seventh installment of an eight-part series on building loader applications in PHP. In this part, you will learn how to use the “spl_autoload(),” “spl_register()” and “spl_register()” functions to build a small file loader class. This class will be able to perform recursive searches through the file system to find a targeted resource.

As the passionate PHP developer that you probably are, you know that building file loading scripts is mostly a process that relies on the set of “include()/include_once()” and “require()/require_once()” functions, which you’ve surely used hundreds of times before.

Nevertheless, it’s feasible to create more efficient and elegant loading scripts by merging the functionality provided by the mentioned functions with that given by the Standard PHP Library (SPL). In truth, it is quite simple to develop short programs that include a specified resource or class using a recursive search through the file system. This process was discussed in depth in previous installments of this series.

But speaking more specifically, in the last tutorial I left off by explaining how to build a small file loading script with the handy “__autoload()” function, which is called by the PHP engine when it finds a reference to a class that hasn’t been included previously.

By giving a customized implementation to the “__autoload()” function, it’s possible to include classes in a transparent way, without having to explicitly call any PHP includes. However, as I mentioned before, the Standard PHP library comes bundled with some helpful functions, such as “spl_autoload(),” “spl_register_extension()” and “spl_autoload_register()” that allow you to either use a default implementation of the “__autoload()” function, or create a custom one for it.

This can be extremely useful when building reusable file loader programs. Thus, over this seventh episode of this series, I’m going to discuss how to use the aforementioned SPL functions to develop a few modular class loader scripts.

Now that you’re aware of the primary goal of this tutorial, it’s time to start learning how to use the Standard PHP library for including classes in a true effective manner. Let’s get going!

{mospagebreak title=Review: the autoload magic function}

Before I start explaining how to use the “spl_autoload()” and “spl_autoload_register()” functions to build a more complex file loading program in PHP 5, first it would be helpful to reintroduce the example developed in the previous article. It was aimed at demonstrating how to create this kind of application by giving a basic implementation to the “__autoload()” function.

Here is the signature of the sample “User” class that needs to be included in a fictional application:

class User

{

private $name = ‘Alejandro’;

private $email = ‘alejandro@domain.com’;

 

// 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;

}

}

And here’s the file loading script that uses the “__autoload()” function for including the “User” class that you just saw:

// 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 depicted above, it’s obviously mandatory to give a concrete implementation to the “__autoload()” PHP function when dynamically loading a required class. Of course, it’s possible to extend the functionality of the example shown before, but for the sake of brevity I’ll keep it that simple for now.

At this stage, you’ve hopefully grasped the logic that stands behind creating class loaders with the “__autoload()” function. But as I stated previously, it needs to be implemented from scratch. However, PHP 5 introduced the “spl_autoload()” function, which offers a default implementation for “__autoload().”

Does all this sound a bit confusing to you? Don’t worry; in the following section I’m going to set up another code sample, which will clearly demonstrate the usage of the “spl_autoload()” function.

To see how this brand new example will be developed, click on the link below and keep reading.

{mospagebreak title=Using the spl autoload extensions and spl autoload functions}

As you saw in the preceding section, it’s pretty simple to implement the “__autoload()” function and build a class loading program very quickly. However, the Standard PHP library includes the “spl_autoload()” function, which has a default implementation for “__autoload().”

To help you understand how this function works, below I coded a whole new example. It shows how to dynamically include the “User” class that you saw before. The example in question looks like this:

// example on using the spl_autoload() function

// register file extensions

spl_autoload_extensions(‘.php,.inc’);

 

// default implementation for the __autoload() function

// load User class

spl_autoload(‘user’);

// create instance of User class

$user = new User();

// display user data

echo $user;

If you closely examine the above script, you’ll realize how simple it is to work with the “spl_autoload()” function. First, the script uses the “spl_autoload_extensions()” to set up the appropriate order of the file extensions for which the PHP engine will look when attempting to load an given class. This can be very convenient for speeding up the whole loading process.

Finally, the “spl_autoload()” function is utilized to dynamically include the aforementioned “User” class via a default implementation of the previous “__autoload().”

Obviously, when it comes to creating class loaders in a few simple steps, the “spl_autoload()” function can be a real time-saver. But what if you need to define a custom method for including your classes? Well, that’s a really easy problem to solve, thanks to the existence of another function of SPL, called “spl_autoload_register().”  As its name suggests, it permits you to register a custom callback function for autoloading classes.

In the last section of this tutorial I’m going to cover the use of this function in detail. Therefore, to learn more about it, click on the link below and keep reading.

{mospagebreak title=Introducing the spl autoload register function} 

As I said in the segment that you just read, the Standard PHP Library comes bundled with a handy function called “spl_autoload_register(),” which allows you to use a callback method or function for automatically loading classes.

To illustrate how to use this function in more detail, below I defined another sample class called “Autoloader(),” whose “autoload()” method will be tied to the function in question.

That being explained, here’s how to use this class in a concrete case:

// example on using the spl_autoload_register() function

// register autoload() method of Autoloader class

 

spl_autoload_register(‘Autoloader::autoload’);

 

// define Autoloader class

class Autoloader

{

public function __construct(){}

 

// autoload specified file

public static function autoload($file)

{

// the path should be defined as a constant or similar

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

$filepath = $_SERVER[‘DOCUMENT_ROOT’] . ‘/loader_classes/’ . $file . ‘.php’;

if (file_exists($filepath))

{

require_once($filepath);

}

else

{

Autoloader::recursive_autoload($file, $path);

}

}

 

// try to load recursively the specified file

public static function recursive_autoload($file, $path)

{

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

{

// search recursively the specified file

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

{

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

{

$path .= ‘/’ . $dir;

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

if (file_exists($filepath))

{

require_once($filepath);

break;

}

Autoloader::recursive_autoload($file, $path);

}

}

closedir($handle);

}

}

}

// create instance of User class (it’s autoloaded by the Autoloader class)

$user = new User();

// display user data

echo $user;

There you have it. As you can see, the “autoload()” method defined within the above class has been linked to the “spl_autoload_register()” function, meaning that this method will be called by the PHP parser when attempting to include a specific class.

Also, the method is capable of performing recursive searches to find the class that needs to be included, as you can see clearly in the prior example. Not too hard to grasp, right?

Finally, with this wrapping code sample I’m finishing this seventh part of the series. As always, feel free to edit and improve all of the examples shown in this article. This way you can arm yourself with a better background in building class loading programs in PHP 5. The experience will be extremely educational, believe me.

Final thoughts

In this seventh installment of the series, you learned how to use the “spl_autoload(),” “spl_register()” and “spl_register()” functions to build an small file loader class which was capable of performing recursive searches through the file system to find a targeted resource.

In this particular case, the recursive algorithm used by the class was rather lengthy and hard to grasp. However, the Standard PHP library includes a set of iterators that allow you to traverse directories in a truly effortless fashion. So, in the last chapter of this series I’m going to incorporate an iterator into the previous loader class, making its source code a bit more compact and readable.

Don’t miss the final tutorial!

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

chat sex hikayeleri Ensest hikaye