Skip to content

Instantly share code, notes, and snippets.

@umidjons
Last active March 14, 2017 23:00
Show Gist options
  • Save umidjons/1c3f9b4dbaf40f618ccd9920750e909d to your computer and use it in GitHub Desktop.
Save umidjons/1c3f9b4dbaf40f618ccd9920750e909d to your computer and use it in GitHub Desktop.
Class autoloading in PHP

Class Autoloading

File Application/Autoload/Loader.php:

<?php
namespace Application\Autoload;

class Loader
{
    const UNABLE_TO_LOAD = 'Unable to load';

    protected static $dirs = [];
    private static $registered = 0;

    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);
            }
            $success = true;
        }

        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 = [])
    {
        if ($dirs) {
            self::addDirs($dirs);
        }

        if (!self::$registered) {
            spl_autoload_register(__CLASS__ . '::autoload');
            ++self::$registered;
        }
    }

    public function __construct($dirs = [])
    {
        self::init($dirs);
    }
}

File Application/Test/TestClass.php:

<?php
namespace Application\Test;

class TestClass
{
    public function getTest()
    {
        return __METHOD__;
    }
}

File index.php:

<?php
require 'Application\Autoload\Loader.php';
\Application\Autoload\Loader::init(__DIR__);

try {
    // existing class
    $test = new Application\Test\TestClass();
    echo $test->getTest();

    // not existing class
    $fake = new Application\Test\FakeClass();
    echo $fake->getFake();
} catch (Exception $e) {
    echo $e->getMessage();
}

Source: Book PHP 7 Programming Cookbook by Doug Bierer

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