TechDingo
TechDingo

Reputation: 184

Why does 'composer dumpautoload -o' fix 'Class not found' PHP error?

I have a Laravel 5.8 project that is dependent on a private package.

When I run composer install the package is installed and shows up in the vendor folder.

project composer.json

{
    ...
    "require": {
        "php": ">=7.0",
        "company/api-request": ">=1.0.0"
    }
    ...
}

package src/ApiRequest.php

<?php

namespace Company;

class APIRequest
{
    ...
}

package composer.json

{
    ...
    "autoload": {
        "psr-4": {
            "Company\\": "src/"
        }
    }
    ...
}

When I call the package

\Company\APIRequest::run();

I am getting

Message: Class 'Company\APIRequest' not found

I know the PHP syntax is correct because when I run composer dumpautoload -o the error is gone, but why is it necessary?

I expect composer install or composer update should be sufficient; I have no problem with external packages.

Am I missing anything here?

Upvotes: 1

Views: 2034

Answers (1)

superbeef150
superbeef150

Reputation: 81

If the class name and file name don't match, that would cause the auto-loading to not work since that is a requirement with PSR-4. From the docs:

The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

If that's the case, composer dumpautoload -o is probably working around this for you, see this Reddit post:

The reason -o works, is Composer creates a giant associative array where classname = filename

Upvotes: 2

Related Questions