Symfony4 加载类自定义文件夹"Expected to find class... but it was not found"时出错



问题

我正在尝试设置自定义目录结构对于我的Symfony项目中的一些共享课程。我想要在我的根部创建一个自定义文件夹项目,我想使用Symfony Auto-Load从自动注册服务的功能该文件夹。

所以我在services.yaml文件:

# src ./config/services.yaml
services:
    ...
    TestNamespace:
    resource: '../TestNamespace/*'
  ...

,我在自定义文件夹中添加了一个空类:

# src ./TestNamespace/TestClass.php
namespace TestNamespace;
class TestClass
{
}

运行应用程序时,我会收到以下错误:

(1/2) InvalidArgumentException
Expected to find class "TestNamespaceTestClass" in file 
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php"
while importing services from resource 
"../TestNamespace/*", but it was not found! Check the
namespace prefix used with the resource.
(2/2) FileLoaderLoadException
Expected to find class "TestNamespaceTestClass" in file 
"/path/to/ClassLoadErrorDemo/demo/TestNamespace/TestClass.php" while 
importing services from resource "../TestNamespace/*", but it was not 
found! Check the namespace prefix used with the resource in 
/path/to/ClassLoadErrorDemo/demo/config/services.yaml (which is loaded 
in resource "/path/to/ClassLoadErrorDemo/demo/config/services.yaml").

我仔细检查了路径,名称空间和类多次命名,一切看起来都很好,我不明白为什么我仍然会遇到错误。./src文件夹中的控制器似乎可以正加载良好。我在这里做错了什么?

复制步骤

我创建了一个演示回购来隔离问题。

git clone https://github.com/smoelker/SymfonyClassLoadErrorDemo.git
cd SymfonyClassLoadErrorDemo/demo
composer install
mv TestNamespace/TestClass.php_ TestNamespace/TestClass.php
php bin/console server:start

更新您的作曲家。

{
    [...]
    "autoload": {
        "psr-4": {
            "TestNamespace\": "TestNamespace/",
            "": "src/"
        }
    },
    [...]
}

运行后:composer dump-autoload,然后重试。

composer dump-autoload --classmap-authoritative仅在运行命令时出现您的src目录时才能工作。

这可能是多级Docker构建的问题,当您通常仅将composer.json/composer.lock复制到构建图像中时。

相关内容

最新更新