Search code examples
phpautoloader

How to use PHP Autoloader in multiple files?


I currently try to replace the requires and require_once's in my project by a autoloader. I'm working with the MVC model and need to autoload a lot of files.

File1: My autoloader class/function looks like this:

<?php

class Autoloader {

    static public function loadEverything() {

        $root = realpath($_SERVER["DOCUMENT_ROOT"]);
        require_once $root . "/src/Model/Device.php";
        require_once $root . "/src/Model/Employee.php";
        require_once $root . "/src/Model/User.php";
        require_once $root . "/src/Controller/Controller.php";
    }

}

File2: And the file I use this files in looks like this:

$root = realpath($_SERVER["DOCUMENT_ROOT"]);
require_once $root . "/src/Model/Autoloader.php";
spl_autoload_register('Autoloader::loadEverything');

But that doesn't work. How do I activate that autoload in File2? I don't get it. Thanks for your help.


Solution

  • That is what you do when you want to autoload your classes:

    function my_autoloader($class) {
        include $root . 'classes/' . $class . '.class.php';
    }
    
    spl_autoload_register('my_autoloader');
    

    If you want to load anything else you can write a new function that gets called where you put all your require_once stuff.

    This works:

    class Autoloader {
    
        static public function loadEverything() {
            $root = realpath($_SERVER["DOCUMENT_ROOT"]);
    
            //Autoloading classes
            spl_autoload_register(function ($class) {
                $root . 'Model/' . $class . '.php';
            });
    
            //Manually load needed files
            require_once $root . "/src/Model/Device.php";
            require_once $root . "/src/Model/Employee.php";
            require_once $root . "/src/Model/User.php";
            require_once $root . "/src/Controller/Controller.php";
        }
    
    }
    
    Autoloader::loadEverything();
    

    If you are new to mvc, you can watch the videos from Codecourse on youtube. He has like 25 videos about a mvc application and he explains everything so nice.