22

问题

我正在尝试为我的 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
4

2 回答 2

42

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

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

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

于 2017-12-23T18:38:59.427 回答
3

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

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

于 2019-01-24T00:03:45.250 回答