Skip to content

Instantly share code, notes, and snippets.

@jcicero518
Created October 3, 2017 19:25
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 jcicero518/583529c447eee05bc234beaa50d5aed8 to your computer and use it in GitHub Desktop.
Save jcicero518/583529c447eee05bc234beaa50d5aed8 to your computer and use it in GitHub Desktop.
Autoloader Class
<?php
namespace Application\Autoload;
class Loader {
const UNABLE_TO_LOAD = 1;
public static $dirs;
public static $registered = 0;
public function __construct($dirs = array()) {
self::init($dirs);
}
protected static function loadFile($file) {
if (file_exists($file)) {
require_once $file;
return TRUE;
}
return FALSE;
}
public static function autoLoad($class) {
$success = false;
$fn = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
foreach (self::$dirs as $start) {
$file = $start . DIRECTORY_SEPARATOR . $fn;
if (self::loadFile($file)) {
$success = true;
break;
}
}
if (!$success) {
if (!self::loadFile(__DIR__ . DIRECTORY_SEPARATOR . $fn)) {
throw new \Exception(self::UNABLE_TO_LOAD . ' ' . $class);
}
}
return $success;
}
public static function addDirs($dirs) {
if (is_array($dirs)) {
self::$dirs = array_merge(self::$dirs, $dirs);
} else {
self::$dirs[] = $dirs;
}
}
public static function init($dirs = array()) {
if ($dirs) {
self::addDirs($dirs);
}
if (self::$registered == 0) {
spl_autoload_register(__CLASS__ . '::autoload');
self::$registered++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment