Advertisement
SirSpamModz

PHP Autoloader

Jul 31st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.35 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. class AutoLoader
  5. {
  6.     /**
  7.     * The location where all the classes are stored.
  8.     *
  9.     * @var string
  10.     */
  11.     protected static $_rootDir = '';
  12.  
  13.     /**
  14.     * Variables to say whether you're already setup the autoloader
  15.     *
  16.     * @var boolean
  17.     */
  18.     protected static $_setup = false;
  19.  
  20.     /**
  21.     * Initializes the auto loader.
  22.     *
  23.     * @param string $rootDir The directory all the classes are located
  24.     */
  25.     public static function setupAutoloader($rootDir)
  26.     {
  27.         if(AutoLoader::$_setup) {
  28.             return;
  29.         }
  30.  
  31.         AutoLoader::$_rootDir = $rootDir;
  32.         spl_autoload_register('AutoLoader::autoload');
  33.  
  34.         AutoLoader::$_setup = true;
  35.     }
  36.  
  37.     /**
  38.     * Will auto load a class by the name of the class.
  39.     *
  40.     * @param string $class The name of the class you're going to be loading.
  41.     *
  42.     * @return boolean
  43.     */
  44.     public static function autoload($class)
  45.     {
  46.         if(class_exists($class)) {
  47.             return true;
  48.         }
  49.  
  50.         $classFile = AutoLoader::classToFile($class);
  51.  
  52.         if(!$classFile) {
  53.             return false;
  54.         }
  55.  
  56.         if(file_exists($classFile)) {
  57.             require_once $classFile;
  58.             return class_exists($class);
  59.         }
  60.  
  61.         return false;
  62.     }
  63.  
  64.     /**
  65.     * Converts the class name to a file path.
  66.     *
  67.     * @param string $class The name of the class you want to resolve the file for.
  68.     */
  69.     public static function classToFile($class)
  70.     {
  71.         return AutoLoader::$_rootDir . '/' . strtolower($class) . '.php';
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement