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.
- <?php
- spl_autoload_register(function($class){
- $classPath = dirname(__FILE__) . '/' . str_replace( "_", "/", $class) .'.php';
- include $classPath;
- });
- $smtp = new System_Mail_Smtp();
- ?>
- <?php
- spl_autoload_register(function($class){
- $classPath = str_replace( "\\", "/", dirname(__FILE__)) . '/' . str_replace(array( "\\", "_"), "/", $class) .'.php';
- include $classPath;
- });
- ?>
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