Search code examples
phpmodel-view-controllerspl-autoload-register

PHP autoloader cant find necessary class


So I am learning PHP MVC for the first time, and i came up to a term - autoloading all the required .php files.

So I searched the web for some examples, and made an autoload file with spl_autoload_register method, calling an anonymous method to require_once all needed files. I don't know what is wrong, but it seems not to work.

So the spl_autoload_register method I made is:

    spl_autoload_register(function($className){
        if(is_file('libraries/' . $className . '.php')){
            echo 'libraries/' . $className . '.php';
            require_once 'libraries/'. $className . '.php';
        }
    });

File structure in the project is available here: https://prnt.sc/gPaVkLZRsPpj

If I comment out the spl_autoload_register method and require all the necessary files one by one, it is working perfectly fine.

    require_once 'libraries/Core.php';
    require_once 'libraries/Controller.php';
    require_once 'libraries/Database.php';

The file in which I'm trying to do the autoload looks like this:

<?php
    require_once '../app/autoload.php';

    // Init Core.php 
    $init = new Core();
    

And the error message I get is:

Fatal error: Uncaught Error: Class "Core" not found in C:\xampp\htdocs\farkops-mvc\public\index.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\farkops-mvc\public\index.php on line 5

I have searched trough the internet, tried other implementations of spl_autoload_register but they all don't work.

Can someone please help me to resolve this issue? :)


Solution

  • So the problem was (as @Lawrence Cherone mentioned in comments), that autoloader was called in context to the current working directory, in which the file that was calling that autoloader was located.

    So I made a few changes.

    1. Made an constant APPROOT, that contains link to app folder (the root folder for all core files)
    define('APPROOT', dirname(dirname(__FILE__)));
    

    In my case, APPROOT is C:\xampp\htdocs\mvc\app

    1. Used that constant to get the right directory with autoloader:
    spl_autoload_register(function($className){
            if(is_file(APPROOT . '/libraries/' . $className . '.php')){
                require_once APPROOT . '/libraries/' . $className . '.php';
            }
        });
    

    And now, autoloader can access filer in folders like C:\xampp\htdocs\mvc\app\libraries\Core.php without any errors.