Up to this point I've used procedural standalone autoloader functions and registered them with spl_autoload_register() to automatically load my (usually) namespaced classes. Lately, though, I've noticed people mentioning the use of autoloader classes in conjunction with some of the prominent PHP frameworks.
Almost all of my code is object oriented these days, but I don't really see advantages to using a class "Autoloader" over a basic function in this instance. And in terms of testability, I feel pretty good about using class_exists() checks in my tests to verify that the procedural functions load files correctly.
So my questions are three:
- What advantages or features (if any) might sway me to refactor things and start using a full blown object to autoload class files?
- Am I missing some glaring advantages here outside the obvious OOP features?
- Could you please make a case for either procedural or class autoloaders?
UPDATE
Below is some example code for a typical autoload function I might employ. It's metacode, so don't look for typos. I organize my directory structures so that they mirror the namespaces. The hypothetical explode_namespaces()
function could theoretically be included as a static method alongside a static autoload()
method in a class, so that's one benefit. It might be cleaner to combine these disparate "utility" functions as methods in a single class.
function autoload($class_name)
{
$root = APP_LIBS; // a directory path constant set at config time
if ($namespaces = explode_namespaces($class_name)) {
$domain = array_shift($namespaces);
$root .= "/$domain/";
$class_name = array_pop($namespaces);
$directories = array();
foreach ($namespaces as $directory) {
$directories[] = $directory;
}
$root .= implode($directories, '/');
}
$file = "$root/$class_name.php";
if (file_exists($file)) {
include $file;
}
}