Search code examples
phpclassherokuautoloader

Problem with autoloader in deploying php website to heroku


I'm having trouble with my autoloader function working properly when my php code is deployed to heroku. I'm using namespaces.

File structure

Heroku log

It works correctly in localhost. I've already made the changes necessary for the paths to translate from localhost to heroku, since heroku uses /app as document root. Thus, in the case below, BASEURL is set to:

define('BASEURL', $_SERVER['DOCUMENT_ROOT']); 

Here's part of the init file:

spl_autoload_register('myAutoLoaderPerson');

function myAutoLoaderPerson($className) {
    $path = BASEURL . '/classes/';      
    $extension = '.class.php';
    $fullPath = $path . $className . $extension;        

    require $fullPath;
}

What am I doing wrong?


Solution

  • Are you sure that $_SERVER['DOCUMENT_ROOT']) is properly filled in?

    I would rather recommend defining BASEURL using some relative definition, e.g., if the Document Root is two folder above the file defining BASEURL:

    define('BASEURL', realpath(__DIR__ . "/../../"));
    

    Or simplifying your autoloader, to make the path relative from it:

    spl_autoload_register('myAutoLoaderPerson');
    
    function myAutoLoaderPerson($className) {
        require_once __DIR__ . "/../../../classes/$className.class.php";
    }
    

    You suggested having /app/classes/lib\foo.class.php being returned.

    Note the mix of / and \. Might be that the difference is that you are on locally, but on remotely.

    If you follow the PSR-4 convention, then it means your namespaces should match directories, but in order to do that, you probably need to transform \ to /.

    Maybe like this:

    spl_autoload_register('myAutoLoaderPerson');
    
    function myAutoLoaderPerson($className) {
        require_once __DIR__ . "/../<path..to>/classes/" . strtr($classname, "\\", "/") . ".class.php";
    }