Composer PSR-4自动加载“找不到类".调试 [英] Composer PSR-4 autoloading "class not found" debug
问题描述
是有关找不到类"错误的另一个问题.我可能丢失了一些东西,或者我误解了PSR-4逻辑.
Yes another question about the "class not found" error. Either I am missing something, or I misunderstood the PSR-4 logic.
我的作曲家库目录结构:
My composer library directory sturcture:
扫描仪" =>"src" =>"Test.php"
"Scanner" => "src" => "Test.php"
Test.php
namespace MyNS;
class Test
{
}
composer.json
composer.json
"autoload": {
"psr-4": {
"MyNS\\": "src/"
},
}
因此,现在我使用composer将库加载到我的项目中,并尝试使用它.
So, now I load the library in my project with composer and try using it.
require_once("../vendor/autoload.php");
$test = new MyNS\Test();
总是导致
致命错误:未捕获的错误:未找到类'MyNS \ Test'."
"Fatal error: Uncaught Error: Class 'MyNS\Test' not found."
.我想念什么?我现在正盯着这几天.我更改了文件夹,更改了文件夹名称,更改了uppper的值,反之亦然.似乎什么都没用.
. What am I missing? I am staring at this for days now. I have changed folders, I have changed folder names, I have changed uppper to lower and vise versa. Nothing seems to work.
我正在使用PHP 7.2.2和Composer 1.2.2版
I am using PHP 7.2.2 and Composer version 1.2.2
甚至尝试过:
require_once("../vendor/autoload.php");
use MyNS\Test;
$scanner = new Test();
更新
我调试了Composer ClassLoader.php文件(findFileWithExtension($ class,$ ext))方法,显然我的文件从未加载过,因为我收到了回声"Done"和die();.在此方法的末尾,这意味着找不到文件,因此未加载该文件.我的composer.json有什么问题?
Update
I debugt the Composer ClassLoader.php file (findFileWithExtension($class, $ext)) method and apparently my files are never loaded because I get put an echo "Done" and a die(); at the end of this method which means the file is not found and thus not loaded. What is wrong with my composer.json?
{
"name": "test/test",
"type": "library",
"description": "",
"keywords": ["php"],
"homepage": "",
"license": "MIT",
"authors": [
{
"name": "",
"email": "",
"homepage": "",
"role": ""
}
],
"require": {
"php": ">=7.2.2"
},
"autoload": {
"psr-4": {
"MyNS\\": "src/"
}
}
}
推荐答案
要调试打开的ClassLoader.php
文件,然后转到定义findFileWithExtension()
方法的位置添加echo
语句:
To debug what is happening open ClassLoader.php
file then go where findFileWithExtension()
method is defined to add an echo
statement:
# vendor/composer/ClassLoader.php:386
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
// Add this line
echo $file, PHP_EOL;
}
在手动完成上述文件的修改后,请不要执行composer dumpautoload
.
现在,通过执行PHP文件,您将在输出的开始看到类似的内容:
Now by executing your PHP file you will see something similar to this at the very beginning of output:
path/to/project/vendor/composer/../../src/Test.php
哪个是:
path/to/project/src/Test.php
这是作曲家正在寻找的文件,并且应包含以下内容:
So this is the file that composer is looking for and should contain something like this:
namespace MyNS;
class Test { }
如果包含文件存在问题,则意味着您必须关心三件事:
If there is an issue in including the file then it means you have to care about three things:
- 路径和文件名
- 文件中使用的命名空间
- 文件中使用的类名(类名应与文件名相同)
这篇关于Composer PSR-4自动加载“找不到类".调试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!