The SplAutoloader Interface

Overview

While any valid PHP callback may be registered with spl_autoload_register(), Zend Framework autoloaders often provide more flexibility by being stateful and allowing configuration. To provide a common interface, Zend Framework provides the SplAutoloader interface.

Objects implementing this interface provide a standard mechanism for configuration, a method that may be invoked to attempt to load a class, and a method for registering with the SPL autoloading mechanism.

Quick Start

To create your own autoloading mechanism, simply create a class implementing the SplAutoloader interface (you may review the methods defined in the Methods section). As a simple example, consider the following autoloader, which will look for a class file named after the class within a list of registered directories.

  1. require_once 'Zend/Loader/SplAutoloader.php';
  2.  
  3. class Custom_ModifiedIncludePathAutoloader implements Zend_Loader_SplAutoloader
  4. {
  5.     protected $paths = array();
  6.  
  7.     public function __construct($options = null)
  8.     {
  9.         if (null !== $options) {
  10.             $this->setOptions($options);
  11.         }
  12.     }
  13.  
  14.     public function setOptions($options)
  15.     {
  16.         if (!is_array($options) && !($options instanceof Traversable)) {
  17.             throw new InvalidArgumentException();
  18.         }
  19.  
  20.         foreach ($options as $path) {
  21.             if (!in_array($path, $this->paths)) {
  22.                 $this->paths[] = $path;
  23.             }
  24.         }
  25.         return $this;
  26.     }
  27.  
  28.     public function autoload($classname)
  29.     {
  30.         $filename = $classname . '.php';
  31.         foreach ($this->paths as $path) {
  32.             $test = $path . DIRECTORY_SEPARATOR . $filename;
  33.             if (file_exists($test)) {
  34.                 return include($test);
  35.             }
  36.         }
  37.         return false;
  38.     }
  39.  
  40.     public function register()
  41.     {
  42.         spl_autoload_register(array($this, 'autoload'));
  43.     }
  44. }

Configuration Options

This component defines no configuration options, as it is an interface.

Available Methods

Examples

Please see the Quick Start for a complete example.

blog comments powered by Disqus