Symfony4加载类自定义文件夹时出错“预计找到类...但是找不到它”

问题描述 投票:8回答:2

问题

我正在尝试为Symfony项目中的某些共享类设置自定义目录结构。我想在项目的根目录中创建一个自定义文件夹,我想使用Symfony自动加载功能自动注册该文件夹中的服务。

所以我在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 "TestNamespace\TestClass" 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 "TestNamespace\TestClass" 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
php symfony symfony4
2个回答
16
投票

更新您的composer.json自动加载设置

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

运行后:composer dump-autoload再试一次。


1
投票

composer dump-autoload --classmap-authoritative仅在您运行命令时存在src目录时才有效。

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

© www.soinside.com 2019 - 2024. All rights reserved.