4
votes

I want to create a new reusable bundle with SF4. I followed the documentation but if I add my new bundle inside the "src" directory, there is a conflict with the App namespace and composer autoloading:

"autoload": {
    "psr-4": {
        "App\\": "src/",
        "Acme\\TestBundle\\": "src/Acme/TestBundle/"
    }
},

Then, I get this error:

PHP Fatal error: Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "AcmeTestBundle" from namespace "Acme\TestBundle".

I think it's because the PSR-4 autoloader loaded the file with the wrong namespace (App/Acme/TestBundle/AcmeTestBundle.php).

Is there a way to fix this issue? I've also tried to create another bundle for my App but then it crash because of the Kernel.php file...

This fallback directory method doesn't work either:

"psr-4": {
    "": "src/"
}
1
I'm unable to replicate this issue. Have you tried running composer dump-autoload? - Andy
Yes I've done that too. Did you follow the documentation instructions? Did you use the Symfony 4 version? - pjehan
Yes, I was able to create the AcmeTestBundle in my Symfony 4 app as per the documentation, using the same PSR-4 autoload config you’re using. Other things to check: is the class named correctly? Are all files and paths named correctly? Does the class have the correct namespace declaration at the top of the file? - Andy
Add Acme to the list of excluded directories in config/services.yaml to get rid of the "name already in use" message. - Cerad
@Cerad Looks like it solved the problem! Could you add your answer so I can validate it? Thanks a lot! - pjehan

1 Answers

0
votes

To help PSR-4 Autoloader to load Acme as a bundle, you must exclude his directory from App services directories :

file: config/services.yaml

services:
        ...
        App\:
        resource: '../src/*'
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        **exclude: '../src/{Entity,Migrations,Repository,Acme}'**