Symfony4加载类自定义文件夹

Symfony4加载类自定义文件夹

本文介绍了Symfony4加载类自定义文件夹“预期要找到类...但未找到"时出错.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to setup a custom directory structurefor some shared classes in my Symfony project. Iwant to create a custom folder in the root of myproject and I want to use the Symfony auto-loadfeature to automatically register services fromthat folder.

因此,我将自定义服务名称空间添加到了services.yaml文件:

So I added a custom services namespace to theservices.yaml file:

# src ./config/services.yaml
services:
    ...

    TestNamespace\:
    resource: '../TestNamespace/*'

  ...

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

And I added an empty class in the custom folder:

# src ./TestNamespace/TestClass.php

namespace TestNamespace;

class TestClass
{

}

当我运行该应用程序时,出现以下错误:

When I run the app I get the following error:

(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文件夹中的控制器似乎可以正常加载.我在这里做错了什么?

I double checked the paths, namespace and the classname multiple times and everything seems fine and Idon't understand why I still get the error.Controllers in the ./src folder seem to load fine.What am I doing wrong here?

我创建了一个示例存储库来隔离问题.

I created a demo repo to isolate the problem.

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

推荐答案

更新composer.json自动加载设置

Update your composer.json autoload setup

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

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

这篇关于Symfony4加载类自定义文件夹“预期要找到类...但未找到"时出错.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:14