Symfony4 Error loading classes custom folder “Expected to find class… but it was not found”

我们两清 提交于 2019-12-21 07:46:05

问题


Problem

I'm trying to setup a custom directory structure for some shared classes in my Symfony project. I want to create a custom folder in the root of my project and I want to use the Symfony auto-load feature to automatically register services from that folder.

So I added a custom services namespace to the services.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").

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

Steps to reproduce

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

回答1:


Update your composer.json autoload setup

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

After run: composer dump-autoload and try again.




回答2:


composer dump-autoload --classmap-authoritative will only work if your src directory is present at the time you run the command.

This can be an issue with multi-stage Docker builds in particular, when you are normally only copying the composer.json/composer.lock into the build image.



来源:https://stackoverflow.com/questions/47954510/symfony4-error-loading-classes-custom-folder-expected-to-find-class-but-it-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!