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:

<br />
require __DIR__ . '/vendor/autoload.php';<br />

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

<br />
{<br />
    &quot;require&quot;: {<br />
        &quot;php&quot;: &quot;&gt;=5.3.0&quot;,<br />
        &quot;slim/slim&quot;: &quot;^3.0&quot;,<br />
        &quot;davidepastore/slim-config&quot;: &quot;^0.1.1&quot;,<br />
        &quot;vlucas/spot2&quot;: &quot;~2.0&quot;<br />
    },<br />
    &quot;autoload&quot;: {<br />
        &quot;psr-4&quot;: {<br />
            &quot;db\\&quot;: &quot;db/&quot;<br />
        }<br />
    }<br />
}<br />

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

<br />
composer dump-autoload<br />

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:

<br />
error_log(&quot;findFileWithExtension -- &quot;.$class);<br />

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:

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

Resources

Leave a Comment

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