php - 无法让我的自动加载器使用命名空间

标签 php namespaces autoload

我的文件夹结构与我的 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 srcmyproject直接,例如。

$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/

相关文章:

php - 为什么方法欺骗不起作用 Laravel?

php - 是否有可能 "pirate" session 变量(我不想知道如何)

xml - 是 xsi : prefix assumed to be known in XML?

php - 找不到 Composer 自动加载类

PHP system() 调用在由 shell 调用时不起作用

php - FedEx express API。运输标签。多件包裹运输

powershell - powershell中的单词分隔符

xml - 使用命名空间在 R 中创建 XML

php - 在 Zend Framework 2 中对同一 namespace 使用两个不同的目录 - 如何?

python - SQLAlchemy 声明式具体自动加载表继承