Menu

Home

James Watts

PHP AutoLoad

The AutoLoad class provides a PSR-0 compatible method to load required classes using namespaces for PHP 5.3+. For a class to the comply with the standard the following criteria must be met:

  • A fully-qualified namespace and class must have the following structure \<Vendor Name>\(<Namespace>\)*<Class Name>
  • Each namespace must have a top-level namespace ("Vendor Name").
  • Each namespace can have as many sub-namespaces as it wishes.
  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • Each _ character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The _ character has no special meaning in the namespace.
  • The fully-qualified namespace and class is suffixed with ".php" when loading from the file system.
  • Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.

Installation

To use the autoloader first include the class:

require 'Solfenix/AutoLoad/AutoLoad.php';

Once the class is available the autoloader needs to be registered, for example:

spl_autoload_register( 'Solfenix\AutoLoad\AutoLoad::run' );

Configuration

The base path where your classes are located can be set if needed, for example:

AutoLoad::setPath( array( 'path', 'to', 'files' ) );

This would resolve to path/to/files/<Vendor Name>/(<Namespace>/)*<Class Name>, however, the namespace would remain the same:

use <Vendor Name>\(<Namespace>\)*<Class Name>;

The extension used for your classes can also be set, for example:

AutoLoad::setExtension( 'class.php' );

This would search for files ending in .class.php, for example:

path/to/files/Solfenix/AutoLoad/AutoLoad.class.php

The file paths of the loaded classes are stored internally by the AutoLoad class.

AutoLoad::getClasses();