38

In regards to Laravel, I got a question about Composer autoloading i.e. the difference between "psr-4" and "classmap" autoloading.

1 difference that I know is PSR-4 does not need repeated dumpautoload for every changes or addition of new files whereas classmap needs dumpautoload for every change in existing files containing classes or addition of new file in specified directory.

halfer
  • 19,824
  • 17
  • 99
  • 186
RoMo
  • 413
  • 1
  • 6
  • 10

1 Answers1

71

PSR-4 standard requires of you a strict filesystem structure based on namespaces. Say you have an app in src directory with App namespace, then all sub-namespaces will mirror subdirectories and class names will be the same as file names without the .php extension.

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

src/
    Foo/
        Bar.php <---- App\Foo\Bar class
    Baz.php <---- App\Baz class

The autoloader then "knows" where to look for the class of a certain fully qualified name and therefore doesn't require the dump-autoload command to sniff files for classes.

Performance issues are then solved with composer dump-autoload --optimize-autoloader flag, or -o, which will generate class map a similar way the classmap autoloading does.


On the other hand, classmap autoloading does not require you to have almost any certain file or directory structure, it will recursively go through .php and .inc files in specified directories and files and sniff for classes in them.

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}

Those classes are then added to a list (cached in a PHP file in vendor/composer directory) which is used for autoloading.

Any new class then must be added to that list by running composer dump-autoload command.

Finwe
  • 6,372
  • 2
  • 29
  • 44
  • what about plain php files without class? e.g. just a php file with a bunch of global functions, how to add that? – Toskan Oct 30 '17 at 21:40
  • 4
    @Toskan For that, use `files`. Eg, `"autoload": { "files": [ "path/to/file1.php", "another/file.php", "etc.php" ] }`. – bishop Mar 08 '20 at 19:22
  • Can classes and files be loaded together, just using the autoload as i have tried this and failed. Both separately fine, but together no dice. – Mike Thornley Jul 28 '20 at 12:39
  • Sure. Just use classmap/psr/files alongside each other. Autoload/dump will fail on duplicate class FQNs, though. If you have a concrete problem, perhaps create a separate question. – Finwe Jul 28 '20 at 14:58