Chapter 4 of the Learn PHP 8 from scratch track
Composer takes over
4 exercises · 450 XP · about 1 h
Composercomposer.jsonJSONDependencyPSR-4Autoloadcomposer dump-autoloadvendor/autoload.phpNamespacesusecomposer dump-autoload -o
The chapter's exercises
-
Reading a composer.json
Exercise 1 · 100 XP · 4 objectives checked by tests
Odette's nephew, him again, explains that “nobody writes their autoloader by hand anymore.” Everyone uses Composer, the tool that manages PHP projects. Good news: the gazette already has a composer.json file. It has been sitting there since the very beginning, and nobody has ever opened it.
Composercomposer.jsonJSONDependency
-
Declaring PSR-4
Exercise 2 · 100 XP · 3 objectives checked by tests
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.
-
Goodbye, homemade autoloader
Exercise 3 · 100 XP · 3 objectives checked by tests
Composer now knows how to load the gazette's classes. Your autoloader served you well: it can retire.
-
Subfolders
Exercise 4 · 150 XP · 5 objectives checked by tests
The src/ folder is filling up, so Madame Lou did some tidying: everything that gets published went into src/Contenu/ (content), and Gaston's weather report into src/Meteo/ (weather). The files have moved, but their namespaces stayed at the old address, and the front page no longer shows.
NamespacesusePSR-4Composercomposer dump-autoload -o