Reputation:
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:
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;
}
}
Upvotes: 15
Views: 3006
Reputation: 145482
You are comparing functions with methods. That's just syntactic sugar.
Unless you have a map-based autoloader or one that has a builtin dependency table you don't need any class-level attributes to keep track of things (or could resort to static or global vars otherwise). Runtime reconfigurability is not a real necessity in practice either.
You can make a procedural autoloader project-configurable with constants etc. Having constructor properties isn't that significant of a benefit for reuse with a method implementation. It only may look slightly nicer.
Upvotes: 4
Reputation: 46040
Use the prebuilt one if you already use another major part of the framework, other wise it doesn't really matter.
Also, using one auto loader, with multiple namespaces/directories registered will cut down memory ever so slightly, but that's not really a concern.
Upvotes: 0