Created
February 22, 2011 17:00
-
-
Save jhbabon/838981 to your computer and use it in GitHub Desktop.
Very simple autoloader class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to understand how composer autoloader work your code help me learn faster ! thanks .