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