I'm a little confused with how I should be using psr-4 autoloading in Composer. Let's say I've got a folder structure like this:
/
|- Core/
| - Router.php
|- App/
| - Models
| User.php
|- composer.json
Basically, in the project root: composer.json; a Core folder containing a Router php class; an App folder containing a Models folder that contains a User class.
The Router class looks like this:
<?php
namespace Core;
class Router {
}
and the Users class looks like this:
<?php
namespace App\Models;
class User {
}
So I can autoload these classes using the Composer psr-4 autoloader, I can do this in composer.json:
{
"autoload": {
"psr-4": {
"Core\\": "Core",
"App\\Models\\": "App/Models"
}
}
}
So I can then use the classes without requiring them (after running composer dump-autoload
) like this:
$router = new Core\Router();
$user = new App\Models\User();
which works with no problems.
However, I can also do this in composer.json:
{
"autoload": {
"psr-4": {
"": ""
}
}
}
which, according to the documentation is a fallback directory where any namespace can be, relative to the root. So by having this "empty" entry in the composer autoloader, which I believe says "starting in the root, look in any directory for a class in any namespace", I can autoload any of my classes if I follow the correct folder naming / namespace structure.
So my question is, why would I do the former if the latter works and is much simpler? Is it a performance thing? Or is there another reason?
Why shouldn't you always do "psr-4": {"": ""}
?
Reason 1: It cost performance. The definition says that for EVERY class that needs autoloading, Composer should look into the root directory. These classes are not only the ones in your package, but ALL other classes as well.
Composer tries to optimizes this effort a bit by remembering fruitless searches, but this only pays if you load another class with the same prefix.
Reason 2: The essence of PSR-4 is that you don't have to have the whole namespace path mapped to a directory path. Assuming that you have a package which deals with a very specific group of classes like \Vendor\Template\Escaping\Output\*
, and nothing else (having small packages makes it easier to reuse them without adding too much code), you can have them in src/Vendor/Template/Escaping/Output/AnyClass.php
and define
"psr-4": {
"\\Vendor\\Template\\Escaping\\Output\\": "src/Vendor/Template/Escaping/Output/"
}
You can also put the class into src/AnyClass.php
and define
"psr-4": {
"\\Vendor\\Template\\Escaping\\Output\\": "src/"
}
And this shortens the directory path significantly, marginally improving speed (I think - have no figures though), but mostly improving developing the thing due to less opening of empty folders.
Having both a Core
namespace and an App
namespace in the same package makes me suspicious: Why isn't there one package for each of these?