Skip to content

Instantly share code, notes, and snippets.

@ivansky
Created September 14, 2014 14:58
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 ivansky/1db08fe01ad52322e070 to your computer and use it in GitHub Desktop.
Save ivansky/1db08fe01ad52322e070 to your computer and use it in GitHub Desktop.
<?php
define('ROOT', $_SERVER['DOCUMENT_ROOT']);
class AutoLoader {
private static $possible = array();
private static $events = array();
public static function load($class){
if(count(self::$events)){
foreach(self::$events as $bind => $event){
if(strpos($class, $bind) == 0){
$event();
}
}
}
$pos = strripos($class, '_');
if($pos){
$prefix = str_replace('_', '/', substr($class, 0, $pos+1));
$suffix = substr($class, $pos+1);
}
$namespaceMarker = strripos($class, '\\');
foreach (self::$possible as $path) {
if($pos){
$outpath = sprintf($path, $prefix.$class);
if(file_exists($outpath)) include_once($outpath);
$outpath = sprintf($path, $prefix.$suffix);
if(file_exists($outpath)) include_once($outpath);
}
$pathNeo = sprintf($path, str_replace('_', '/', $class));
$pathNamespaced = sprintf($path, str_replace(chr(92), '/', $class));
$path = sprintf($path, $class);
if(file_exists($path)) include_once($path);
if(file_exists($pathNeo)) include_once($pathNeo);
if($namespaceMarker && file_exists($pathNamespaced)) include_once($pathNamespaced);
}
}
public static function register($path){
$path = str_replace('{ROOT}', ROOT, $path);
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
self::$possible[] = $path;
}
public static function registerEvent($bind, $event){
if($bind && is_callable($event)){
self::$events[$bind] = $event;
}
}
}
AutoLoader::register('{ROOT}/core/%s.php');
AutoLoader::register('{ROOT}/core/models/%s.php');
AutoLoader::register('{ROOT}/core/components/%s.php');
AutoLoader::register('{ROOT}/core/controllers/%s.php');
AutoLoader::register('{ROOT}/core/lib/%s.php');
AutoLoader::registerEvent('Swift', function(){
include_once ROOT . '/core/lib/SwiftInit.php';
});
spl_autoload_register('AutoLoader::load');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment