Thursday, October 27th, 2011

PHP Autoloader – Building Your Own Register

By , Software Developer

Although rife with a slew of inefficiencies and idiosyncrasies, PHP does offer the scripter a powerful set of possibilities for the energetic and inclined. One of these is its autoload concept – it isn’t unique to PHP, but PHP offers a certain degree of simplicity to the scripter who is willing to follow some basic conventions.

Before namespaces were available, most PHP programmers used the name of their class to indicate the path to the file in which it was defined. So, if there were a class in path “./Model/Nature/Tree.php”, then it would be named “Model_Nature_Tree”. This way, the autoload method can split the class name by underscores and build the path.

Here is a basic implementation: http://pastie.org/2663927

However, this leads to painfully long class names (the entire path from the root) or restricts you to only loading classes from a designated library directory — in the example above, perhaps “Model.”

This strategy may be manageable for a small project, or even a large one, but once testing and alternate entry points enter the picture, it becomes a huge hassle to keep your autoloading in sync and keep your class names concise.

PHP 5.1.2 introduced the spl_autoload_register() method, which effectively allowed you to create a queue of autoload methods such that if the class was not found by the first autoload method, the subsequent method would be attempted, and so forth, eventually ending in a class not found exception.

The problem with this solution is that it doesn’t provide an ability to communicate state between the autoload methods or enforce a single entry point from your application into the autoload stack. Instead it leads you to a situation of never being confident of where an autoload is being registered, who is doing it, or which of your autoload methods are successful.

We chose to deal with this situation by creating a class to act as our own autoload register. Since our convention for parsing the class name into a path is respected throughout the entire app, the only difference becomes the starting point. Therefore, we created a class that could manage a queue of load paths where we could search for class files. The class has two methods exposed, one which lets code register a load path into the queue, and the other to be called by the PHP autoloader.

Doing this allows us to (most importantly) define an entire set of load paths for our unit tests without worrying about them interfering with the rest of the code.

Follow this link for the class itself, http://pastie.org/2663962. You should recognize the path_to_class method at the bottom.

Post by Ben VanEvery, Software Engineer

By ,

Software Developer

See all of Ben's articles.