Before we implement a PSR-0 autoloader, we need to pick a directory location in the codebase to hold every class that will ever be used in the codebase. Some projects already have such a location; it may be called includes, classes, src, lib or something similar.

If a location like that already exists, examine it carefully. Does it have only class files in it, or is it a combination of class files and other kinds of files? If it has anything besides class files in it, or if no such location exists, create a new directory location and call it classes (or some other properly descriptive name).

This directory will be the central location for all classes used throughout the project. Later, we will begin moving classes from their scattered locations in the project to this central location.

Perhaps the most straightforward way to implement our new autoloader code is as a global function. Below, we find the autoloader code to use; the function name is prefixed with mlaphp_ to make sure it does not conflict with any existing function names.

Note that the $dir variable represents an absolute directory as the base path for our central class directory. As an alternative on PHP 5.3 and later, it is perfectly acceptable to use the __DIR__ constant in that variable so the absolute path is no longer hard-coded, but is instead relative to the file where the function is located. For example:

If you are stuck on PHP 5.2 for some reason, the __DIR__ constant is not available. You can replace dirname(__DIR__) with dirname(dirname(__FILE__)) in that case.

This is my preferred way of setting up an autoloader. Instead of using a function, we create the autoloader code in a class as an instance method or a static method. I recommend instance methods over static ones, but your situation will dictate which is more appropriate.

First, we create our autoloader class file in our central class directory location. If we are using PHP 5.3 or later, we should use a proper namespace; otherwise, we use underscores as pseudo-namespace separators.

The following is a PHP 5.3 example. Under versions earlier than PHP 5.3, we would omit the namespace declaration and name the class Mlaphp_Autoloader. Either way, the file should be in the sub-path Mlaphp/Autoloader.php:

Then, in the setup or bootstrap file, require_once the class file, instantiate it if needed, and register the method with SPL. Note that we use the array-callable format here, where the first array element is either a class name or an object instance, and the second element is the method to call:

Please pick either an instance method or a static method, not both. The one is not a fallback for the other.