Declaring PSR-4

Exercise 2 of 4 in chapter 4 · 100 XP · 3 objectives checked by tests

Topics covered: PSR-4ComposerAutoloadcomposer dump-autoload

The autoloader you wrote in the previous chapter follows a simple rule: the Gazette\ prefix matches the src/ folder. This rule is so common that it has a name, PSR-4, and Composer knows how to apply it. All you have to do is declare it.

Your mission

  1. In composer.json, add an autoload section, at the same level as require (not inside it), that maps, with PSR-4, the Gazette\ prefix to the src/ folder.
  2. In the console, run composer dump-autoload: Composer rereads composer.json and regenerates vendor/autoload.php.
  3. Run the tests. They load Gazette\Article without your autoloader, using only Composer's.

public/index.php keeps its autoloader for now: you'll replace it in the next exercise.

Reminder

PSR-4 is a recommendation shared by PHP projects: a namespace prefix matches a folder, and the rest of the class name matches the path of the file. Gazette\Meteo\Bulletin lives in src/Meteo/Bulletin.php. Composer doesn't reread composer.json on every request: after changing the autoload section, run composer dump-autoload again.