1

In Symfony4 projects, I'd like to autoload classes defined in the src folder but whose namespace does not start with App. Let's say it starts with Acme instead.

I was expecting that the following configuration in composer.json to work, but it doesn't and I'm getting class not found exceptions:

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

What am I missing here?

David
  • 2,603
  • 4
  • 18
  • 28
  • Have you tried running `composer dump`? – Tomas Votruba Sep 27 '18 at 15:28
  • Yes, I did `composer dump-autoload`. – David Sep 27 '18 at 15:40
  • 2
    I have ran into this before. For some reason Acme\MyAcme always gets changed to App\MyAcme. Moving your Acme classes into their own directory such as srcAcme works. Never understood this behavior. But life is short. – Cerad Sep 27 '18 at 16:28
  • Why do you need such logic anyway? "classmap" is solution for non-PSR naming. After you standardize your namespaces, you can switch to PSR4 autoloading – Tomas Votruba Sep 27 '18 at 18:23
  • Hah. I finally remembered what I figured out quite some time ago. The problem is actually with autowire scanning all files and trying to make services out of them. The App portion of services.yaml indicates that all files under it are part of the App namespace. Exclude your Acme classes or move them to a different directory under src and tweak the resource section and all will be well. – Cerad Sep 27 '18 at 19:44

2 Answers2

1

I have no proof, but I don't think you can use the same namespace in the same directory.

There might be App\SomeClass and Acme\SomeClass and composer would look for both of them in src/SomeClass.php.

You can use classmap autoload for non-standard naming. You should have App\ in /src, so it should be like:

{
    "autoload": {
        "psr-4": {
            "App\": "src"
        },
        "classmap": "src"
    }
}

But I recommend having PSR-4 paths standard everywhere, to prevent such WTFs. In your case renaming Acme to App.

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
  • Will try, thank you. Note that the idea came to me while reading this thread response: https://github.com/symfony/flex/issues/93#issuecomment-305722625. I supposed that it would work since no one shouted on the thread! XD – David Sep 27 '18 at 16:18
  • 1
    It is not a composer/autoload issue. Something in Symfony actually changes the namespace. Don't know how. php itself is fine with multiple namespaces in one directory. – Cerad Sep 27 '18 at 16:30
0

for me, this is working

    "autoload": {
    "psr-4": {
        "": "src/"
    }
},
habibun
  • 1,552
  • 2
  • 14
  • 29
  • Nice edit and that is the way things used to work but not for S4. Make a quick test case and try it. – Cerad Sep 27 '18 at 17:39