Show DevBest [PHP] Easy class & interface loading with automatic initializing

MayoMayn

BestDev
Oct 18, 2016
1,423
683
Basically a better version of spl_autoload_register since it only tries to require the class file whenever you initializes the class.
Here it automatically gets every file inside your class folder, requires the files and initializes it. All you have to do, is name the class the same as the file.
index.php
PHP:
// Require loader
require_once __DIR__ . '/app/autoload.php';
 // Initialize loader
$loader = new Loader(false);
 // Test
User::dump(['hello' => 'test']);
// Get count of how many classes there has been loaded
echo $loader->count;
autoload.php
PHP:
class Loader
{

    private static $library = [];

    protected static $classPath = __DIR__ . "/classes/";

    protected static $interfacePath = __DIR__ . "/classes/interfaces/";

    public $count = 1;

    public function __construct($requireInterface = true)
    {
        if(empty(static::$library)) {
            // Get all files inside the class folder
            foreach(array_map('basename', glob(static::$classPath . "*.php", GLOB_BRACE)) as $classExt) {
                // Get rid of php extension easily without pathinfo
                $classNoExt = substr($classExt, 0, -4);
                // Make sure the class is not already declared somewhere else
                if(!in_array($classNoExt, get_declared_classes())) {
                    $file = static::$classPath . $classExt;

                    if($requireInterface) {
                        // Get interface file
                        $interface = static::$interfacePath . $classExt;
                        // Check if interface file exists
                        if(!file_exists($interface)) {
                            // Throw exception
                            die("Unable to load interface file: " . $interface);
                        }

                        // Require interface
                        require_once $interface;
                        //Check if interface is set
                        if(!interface_exists("Interface" . $classNoExt)) {
                            // Throw exception
                            die("Unable to find interface: " . $interface);
                        }
                    }

                    // Require class
                    require_once $file;
                    // Check if class file exists
                    if(class_exists($classNoExt)) {
                        // Set class        // class.container.php
                        static::$library[$classNoExt] = new $classNoExt();
                        $this->count++;
                    } else {
                        // Throw error
                        die("Unable to load class: " . $classNoExt);
                    }

                }
            }
        }
    }
You can easily manage with a bit of coding, to require classes in different folders too.
Hopefully this can be of some use to any of you.
 
Last edited:

Berk

berkibap#4233
Developer
Oct 17, 2015
863
190
Basically a better version of spl_autoload_register since it only tries to require the class file whenever you initializes the class.
Here it automatically gets every file inside your class folder, requires the files and initializes it. All you have to do, is name the class the same as the file.
index.php
PHP:
// Require loader
require_once __DIR__ . '/app/autoload.php';
 // Initialize loader
$loader = new Loader(false);
 // Test
User::dump(['hello' => 'test']);
autoload.php
PHP:
class Loader
{

    public static $library;

    protected static $classPath = __DIR__ . "/classes/";

    protected static $interfacePath = __DIR__ . "/classes/interfaces/";

    public function __construct($requireInterface = true)
    {
        if(!isset(static::$library)) {
            // Get all files inside the class folder
            foreach(array_map('basename', glob(static::$classPath . "*.php", GLOB_BRACE)) as $classExt) {
                // Get rid of php extension easily without pathinfo
                $classNoExt = substr($classExt, 0, -4);
                // Make sure the class is not already declared
                if(!in_array($classNoExt, get_declared_classes())) {
                    $file = static::$classPath . $classExt;

                    if($requireInterface) {
                        // Get interface file
                        $interface = static::$interfacePath . $classExt;
                        // Check if interface file exists
                        if(!file_exists($interface)) {
                            // Throw exception
                            die("Unable to load interface file: " . $interface);
                        }

                        // Require interface
                        require_once $interface;
                        //Check if interface is set
                        if(!interface_exists("Interface" . $classNoExt)) {
                            // Throw exception
                            die("Unable to find interface: " . $interface);
                        }
                    }

                    // Require class
                    require_once $file;
                    // Check if class file exists
                    if(class_exists($classNoExt)) {
                        // Set class        // class.container.php
                        static::$library[$classNoExt] = new $classNoExt();
                    } else {
                        // Throw error
                        die("Unable to load class: " . $classNoExt);
                    }

                }
            }
        }
    }

    /*public function get($class)
    {
        return (in_array($class, get_declared_classes()) ? static::$library[$class] : die("Class <b>{$class}</b> doesn't exist."));
    }*/
}
You can easily manage with a bit of coding, to require classes in different folders too.
Hopefully this can be of some use to any of you.
quite nice, tysm!
 

MayoMayn

BestDev
Oct 18, 2016
1,423
683
quite nice, tysm!
Was bored, so coded this with selection of desired directories:
index.php
PHP:
require_once __DIR__ . '/app/autoload.php';

$container = new Container([
    'dir' => 'utilities',
    'folders' => [
        'controllers',
        'models'
    ]
]);

echo $container->count; // 3
autoload.php
PHP:
class Container
{

    public static $library = [];

    public $count = 1;

    public function __construct($dir = [])
    {
        if(empty(static::$library)) {
            $folders = implode(",", $dir['folders']);
            // Get all files inside the class folder
            foreach(glob(__DIR__ . "/" . $dir['dir'] . "/{{$folders}}/*.php", GLOB_BRACE) as $file) {
                // Get basename of the file without path
                $base = basename($file);
                // Get name of the file without extension
                $class = substr($base, 0, -4);
                // Make sure the class is not already declared somewhere else
                if(!array_key_exists($class, get_declared_classes())) {
                    // Check whether or not interfaces should be included
                    if(!isset($dir['interfaces_disabled']) || $dir['interfaces_disabled'] == false) {
                        // Get length of file
                        $length = strlen($base);
                        // Set path for the interface file
                        $interface = substr($file, 0, -$length) . "interfaces/".$base;
                        // Check if interface file exists
                        if(file_exists($interface)) {
                            // Set interface
                            require_once $interface;
                            // Check if interface exists
                            if(!interface_exists("Interface".$class)) {
                                // Throw error
                                die("Unable to load interface: Interface".$class);
                            }
                        } else {
                            // Throw error
                            die("Unable to find interface file: " . $interface);
                        }
                    }
                    // Require class
                    require_once $file;
                    // Check if class file exists
                    if(class_exists($class)) {
                        // Set class
                        static::$library[$class] = new $class();

                        $this->count++;
                    } else {
                        // Throw error
                        die("Unable to load class: " . $class);
                    }

                }
            }
        }
    }

    public static function get($class)
    {
        return static::$library[$class];
    }

}
 
Last edited:

MayoMayn

BestDev
Oct 18, 2016
1,423
683
Well, @Wess you asked and I decided to code it. Could use some changes etc, just gonna post it for now.
index.php
PHP:
// Require app autoload
require_once __DIR__ . '/app/autoload_namespace.php';

$class = new Syberia\Autoload([
    Syberia\Http\Request::class,
    Syberia\Controller\Home::class
]);

autoload_namespace.php
PHP:
namespace Syberia;

class Autoload
{

    public static $library = [];

    public function __construct($dir = [])
    {
        if(empty(static::$library)) {
            foreach($dir as $class) {
                // Get the class file
                $name = explode('\\', $class);
                $file = str_replace($name[0], __DIR__ . '/utilities', $class);
                $file = str_replace('\\', '/', $file);
                $file = $file . '.php';
                // Make sure the class is not already declared somewhere else
                if(!array_key_exists($class, get_declared_classes())) {
                    // Check if class file exists
                    if(file_exists($file)) {
                        // Require class
                        require_once $file;
                        // Check if class file exists
                        if(class_exists($class)) {
                            // Set class
                            static::$library[$class] = new $class();
                        } else {
                            // Throw error
                            die("Unable to load class: " . $class);
                        }
                    } else {
                        // Throw error
                        die("Class file {$file} doesn't exist with class " . $class);
                    }
                } else {
                    // Throw error
                    die("Class {$class} already declared.");
                }
            }
        }
    }

    public static function get($class)
    {
        return static::$library[$class];
    }

    public static function clear($class = null)
    {
        $class = (!is_null($class) ? static::$library[$class] : static::$library);
        unset($class);
    }

}

EDIT: forgot it wasnt stackoverflow code syntax
 
Last edited:

Users who are viewing this thread

Top