Why specify the namespace when using psr-4 autoloading with Composer?

Viewed 10875

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?

3 Answers
Related