Composer 自动加载 psr-4 问题

Composer Autoload psr-4 issue

我是作曲家的新手,所以请多多包涵, 所以我有一个包,我正在从本地文件夹加载它,在使用它时,我收到以下错误:

Fatal error: Class 'mypkg\Layer\EasyCPT' not found in C:\xampp\htdocs\testwp\app\Cpt\location.php on line 5

我的Composer.json:

"repositories": [
    {
        "type":"vcs",
        "url":"C:/xampp/htdocs/mypkg"
    }
],
"require": {
    "php": ">=7.0.0",
    "mypkg/particles": "master"
},
"autoload": {
    "psr-4": {
       "App\": "app/"
    }
}

包的编写者:

"minimum-stability": "dev",
"authors": [
    {
        "name": "Talha Abrar",
        "email": "talha@themegeek.io"
    }
],
"autoload": {
    "psr-4": {
       "Mypkg\": "particles/"
    }
}

第 4 篇文章:

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Mypkg\' => array($vendorDir . '/Mypkg/particles/particles'),
    'App\' => array($baseDir . '/app'),
);

我是如何使用它的:

<?php 

namespace App\Cpt;
use Mypkg\Layer\EasyCPT;

class Location extends EasyCPT{
    protected $plural = 'locations';
}

主要自动加载文件:

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

use App\Init\EasyWP;

    new EasyWP();

您将命名空间用作:

use Particles\Layer\EasyCPT;

但在 autoload 部分定义为:

"Mypkg\": "particles/"

不一致。

您应该将 Mypkg 替换为正确的命名空间名称,例如

"autoload": {
    "psr-4": {
       "Particles\": "particles/"
    }
}

因此请求 Particles\Layer\EasyCPT 命名空间将在 particles/Layer/EasyCPT.php 文件中查找 class。

根据Composer's PSR-4 documentation

Under the psr-4 key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like Foo\Bar\Baz a namespace prefix Foo\ pointing to a directory src/ means that the autoloader will look for a file named src/Bar/Baz.php and include it if present. Note that as opposed to the older PSR-0 style, the prefix (Foo\) is not present in the file path.

如果您的项目不遵循 PSR-4 方法,请改用 classmap 扫描所有 classes,例如

"autoload": {
    "classmap": ["particles/"],
    "exclude-from-classmap": ["/tests/"]
}

要手动重新生成 autoload,运行:

composer dump-autoload -o

并检查 vendor/composer/ 中的自动加载文件是否正确生成了对 classes 的引用。