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

别等时光非礼了梦想. 提交于 2020-01-25 00:20:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/58626122/why-does-composer-dumpautoload-o-fix-class-not-found-php-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!