PHP - Autoloading Class Files

Many PHP web frameworks have implementations to autoload class files without the need to use include functions throughout your code. In this articles I'll explain how you can write your own class autoloader.

Before namespaces were introduced in PHP, developers would prepend class names with the directory names leading to the class. For example, if the class Smtp was located at the following path from the root folder '~/System/Mail/Smtp.php' then it's class name would be System_Mail_Smtp. The underscore in the class name is used as a directory separator.

With the class name structure defined, it was a simple case of using either spl_autoload or spl_autoload_register function to load the class file. Although this technique worked well, it became cumbersome when dealing with very long class names such as System_Mail_Transport_Protocol_Smtp.

Before we move on to namespaced classes, let's take a look at how to autoload a class file.

  1. <?php   
  2.   
  3.     spl_autoload_register(function($class){   
  4.         $classPath = dirname(__FILE__) . '/' . str_replace( "_""/", $class) .'.php';    
  5.         include $classPath;   
  6.     });   
  7.   
  8.     $smtp = new System_Mail_Smtp();   
  9.   
  10. ?>  
In the code sample above, the spl_autoload_register registers a callback function. This callback function is called whenever a class is being instantiated. The callback function accepts the name of the class being instantiated. Using the class name, the code replaces all underscores with a '/' and appends '.php' at the end resulting in a file path. Additionally the dirname() function is used to determine the current execution path therefore resulting in an absolute path to the class file. Finally once the path has been determined the include construct loads the file. The same principle can also be applied to namespaced class files. The difference is that the class name supplied to the callback function will include the namespace. All you need to do is replace the '\' backslash that is used in namespaces with '/' since Unix like OS use '/' as the directory separator. With minor changes to the code above you can load classes from both cases.

  1. <?php   
  2.   
  3.     spl_autoload_register(function($class){   
  4.         $classPath = str_replace( "\\""/", dirname(__FILE__)) . '/' . str_replace(array( "\\",  "_"),  "/", $class) .'.php';   
  5.         include $classPath;   
  6.     });   
  7.   
  8. ?>  


This type of autoloading has become a standard across many applications. It's know as PHP Standards Recommendation #0 (PSR-0). There are a few rules you should follow should you want your autoloader to be compliant. These rules can be found on the PHP website for further reading.

No comments:

Post a Comment