chanchal118
chanchal118

Reputation: 3657

Understanding PSR-4

I have file structure like:

├─ vendor/
└─ src/
   ├─ Acme/
   │  ├─ Foul/
   │  │   └─ Nest.php
   │  └─ Universal.php
   └─ Foo.php

I am trying to use PSR-4 auto loading using Composer. This code:

$obj = new Acme\Universal();

Gives me an error: Fatal error: Class 'Acme\Universal' not found in ...

If I use this snippet in composer.json:

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

But if I use

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

everything works fine. I can even access

$otherObj = new Acme\Foul\Nest();

Please note that I have run composer install every time I changed the composer.json file.

Upvotes: 1

Views: 277

Answers (1)

Wouter J
Wouter J

Reputation: 41954

PSR-4 does not include the prefix in the path to search for, PSR-0 does.

So Acme\Universal with "Acme\\": "src/" will be searched in src/Universal.php with PSR-4 and in src/Acme/Universal.php with PSR-0.

In this case, you should move the contents of the src/Acme/ directory to src/. The PSR-4 was created exactly to remove these directories with only one subdirectory and no other files.

Upvotes: 3

Related Questions