我的文件夹结构与我的 PHP 文件及其命名空间存在问题。
这是我的文件夹结构:
myproject
|
-- entry.php
-- src
|
-- IndexController.php
我的
entry.php
看起来像这样:<?php
spl_autoload_register(function (String $class) {
$sourcePath = __DIR__ . DIRECTORY_SEPARATOR . 'src';
$replaceRootPath = str_replace('myproject\Controllers', $sourcePath, $class);
$replaceDirectorySeparator = str_replace('\\', DIRECTORY_SEPARATOR, $replaceRootPath);
$filePath = $replaceDirectorySeparator . '.php';
if (file_exists($filePath)) {
require($filePath);
}
});
$indexController = new myproject\Controllers\IndexController;
$result = $indexController->controlSomething('this thing');
print($result);
我的
src/IndexController.php
看起来像这样:<?php
namespace myproject\Controllers;
class IndexController
{
public function controlSomething(string $something): string {
return $something;
}
}
这工作得很好。但是,我想要一些不同的文件夹结构。我想深入一个文件夹,让我的 Controller 在某个地方井井有条。所以我想要一个
Controllers
文件夹来保存我的 Controller 。将我的文件夹结构更改为:myproject
|
-- entry.php
-- src
|
-- Controllers
|
-- IndexController.php
导致错误提示
Class 'myproject\Controllers\IndexController' not found
.我怎样才能做到这一点?我试过添加
/Controllers
到定义路径和命名空间的代码,但我不断收到此错误。
最佳答案
在您当前的设置中,您已映射文件夹 src
到基本命名空间 myproject\Controllers
.无论后面是什么 myproject\Controllers
, 预计会镜像从 src
开始的子目录结构.
以下是:当您输入 IndexController
时在目录src\Controllers
,只有当完整的类名是 myproject\Controllers\Controllers\IndexController
时,自动加载器才会找到它。 .
您可能想做的是 map src
至 myproject
直接,例如。
$replaceRootPath = str_replace('myproject', $sourcePath, $class);
我倾向于使用的解决方案是使用 composer,也是当前 php 的行业标准。作为自动加载器。
安装后,配置您的自动加载器将变得像这个 json 段一样简单:
"autoload": {
"psr-4": {
"myproject\\": "src"
}
},
并且,可选地,
"autoload-dev": {
"psr-4": {
"myproject\\Test\\": "tests"
}
},
使用 composer 的另一个好处是能够从大量开源模块中提取来简化你的生活。
关于php - 无法让我的自动加载器使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57483945/