Skip to content

Instantly share code, notes, and snippets.

@jhbabon
Created February 22, 2011 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhbabon/838981 to your computer and use it in GitHub Desktop.
Save jhbabon/838981 to your computer and use it in GitHub Desktop.
Very simple autoloader class
<?php
/**
* Very simple autoloader class
*
* This class loads another classes following the Zend naming convention:
* - Class name: Foo_Bar
* - File name: Foo/Bar.php
*
* Example of use:
* > require_once('path/to/Autoloader.php');
* > Autoloader::init();
* > $bar = new Foo_Bar();
*
* @package autoload
**/
class Autoloader {
/**
* File extension for the class files
*
* @var string
**/
protected static $_extension = '.php';
/**
* Directory separator for the file name
*
* @var string
**/
protected static $_dirSeparator = '/';
/**
* Name separator for the namespaces in the file name
*
* @var string
**/
protected static $_nameSeparator = '_';
/**
* Initialize the autoload system
*
* @param string $autoloader The class that act as autoloader. Defaults to self.
* @return boolean
**/
public static function init($autoloader = __CLASS__) {
return spl_autoload_register($autoloader . '::load');
}
/**
* Load the class
*
* @param string $class The class to load
* @return void
**/
public static function load($class) {
$file = self::generateFileName($class);
if (file_exists($file)) {
require_once($file);
} else {
throw new Exception('Class ' . $class . ' not exists');
}
}
/**
* Generate the name of the class file
*
* @param string $class The class name
* @return string The file name
**/
protected static function generateFileName($class) {
$file = str_replace(
self::$_nameSeparator,
self::$_dirSeparator,
$class
);
return $file . self::$_extension;
}
} // END class Autoloader
@sajjadRabiee
Copy link

I want to understand how composer autoloader work your code help me learn faster ! thanks .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment