0

Ordinarily I see complex autoloading solutions that require the user to hydrate them with a pre-defined set of paths/directories with which to look through when autoloading a class. Or they have a complex glob-like search which then builds a cache file to reduce the lookup time etc.

However, I noticed that as long as you namespace each class, and those namespaces match the directory structure that contains them, then your autoloader does not need to be any more complicated than this:

spl_autoload_register(function ($class) {
    include $class . '.php';
});

Assuming you don't have to work with non-namespaced 3rd party classes, is there ever a reason NOT to namespace your classes according to your folder structure, and then let spl_autoload_register handle everything for you?

Is there a pitfall to this that I am overlooking?

AgmLauncher
  • 7,070
  • 8
  • 41
  • 67

1 Answers1

0
<?php

/**
 * Ultra fast class autoloader.
 *
 * @param string $class
 *   Fully qualified class name (automatically passed to this magic function by PHP).
 */
function __autoload($class) {
  static $ds = DIRECTORY_SEPARATOR;
  $class = strtr($class, "\\", DIRECTORY_SEPARATOR);
  require "{$_SERVER["DOCUMENT_ROOT"]}{$ds}src{$ds}{$class}.php";
}

?>

What's good about it?

  • I can't think of any faster implementation
  • It's an ordinary function and not a closure
  • The magic function is called before the SPL loaders
  • Works on all platforms (DIRECTORY_SEPARATOR)
  • It creates absolute paths for inclusion (Linux path/file cache)
  • It doesn't concatenate strings, instead it embeds the string parts
  • strtr() is the fastest string replace function

Drawbacks

  • As long as your classes fit the directory structure: none
  • If you want to include libraries or stuff from other people (e.g. composer) you have a problem, your autoloader will be overwritten and those files won't be loaded (if this isn't a requirement, no need to worry)
Fleshgrinder
  • 15,703
  • 4
  • 47
  • 56