Troubleshooting PHP Composer Class Autoloading

I had some issues with using the Composer autoloading in PHP. So, here’s my notes….

First, here’s how to make it happen. At the top of the file, you have to place this line at the top:

require __DIR__ . '/vendor/autoload.php';

Then, in the composer.json file, you have to include the “autoload” section. Here’s what my file looks like:

{
    "require": {
        "php": ">=5.3.0",
        "slim/slim": "^3.0",
        "davidepastore/slim-config": "^0.1.1",
        "vlucas/spot2": "~2.0"
    },
    "autoload": {
        "psr-4": {
            "db\\": "db/"
        }
    }
}

Everytime you make changes to the autoload section, you have to run this command:

composer dump-autoload

Troubleshooting

I had the path wrong, and I couldn’t figure it out. So, I added some troubleshooting statements.

File: vendor/composer/ClassLoader.php

In the function findFileWithExtension(), add the following line at the top:

error_log("findFileWithExtension -- ".$class);

That shows what classes it is trying to load. The next error_log() I put in the foreach so that I could see in what directories it was looking:

foreach ($this->prefixDirsPsr4[$search] as $dir) {
    $length = $this->prefixLengthsPsr4[$first][$search];
    error_log("dir -- ".$dir);
    if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
        return $file;
    }
}

Resources

Leave a Comment

Your email address will not be published. Required fields are marked *