子文件夹中的 Symfony 4 控制器产生错误

Symfony 4 controllers in sub folders producing error

关于我为什么收到这个的简单问题

The autoloader expected class "App\Controller\Admin\AdminUnitController" to be defined in file "/home/glen/public_html/businessdirectory.glendev.local/vendor/composer/../../src/Controller/Admin/AdminUnitController.php". The file was found but the class was not in it, the class name or namespace probably has a typo in /home/glen/public_html/businessdirectory.glendev.local/config/services.yaml (which is loaded in resource "/home/glen/public_html/businessdirectory.glendev.local/config/services.yaml").

我有 AdminUnitController.php,class 名称为 AdminUnitController。一切都很好,直到我决定将管理控制器放在它们自己的子文件夹中,如下所示:

Controller\Admin\AdminUnitController.php

从自动加载器消息来看,你的问题很清楚,你的文件确实在它应该在的地方但是你的 class 或命名空间是错误的。

我猜你更改了文件结构但没有调整你的命名空间。

给定文件src\Controller\Admin\AdminUnitController.php

你的 class 应该是这样的(特别注意命名空间):

<?php

namespace App\Controller\Admin;

class AdminUnitController 
{
    // some code here
}

这实际上不是您在这里面对的 Symfony 行为,而是作曲家之一,它为 Symfony 提供自动加载器并使用 PSR-4 class 自动加载约定。

供参考

1) 查看你的 composer.json 有那些行:

{
  // some definitions here
  "autoload": {
    "psr-4": {
      "App\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "App\Tests\": "tests/"
    }
  },
  // some more definitions here
}

2) 请参阅 PSR-4 命名约定:尤其是其文档中的示例:https://www.php-fig.org/psr/psr-4/#3-examples