PHP
The composer.json file
Learn the composer.json structure and its basic fields.
The structure of the config file
Composer's config file carries the project's dependencies and autoload settings. The name field holds the package name in vendor/project form. The require section lists packages and versions needed in production. The require-dev section holds packages needed only during development (test, linter). The autoload section defines the PSR-4 mapping; for example the App\ to src/ pair binds the App namespace to the src/ folder.
autoload and the PSR-4 mapping
The autoload section lets class file paths be found automatically. The PSR-4 subsection binds namespaces to folders: with the App\ to src/ pair, the App\Models\User class is loaded from src/Models/User.php.
After install, Composer produces vendor/autoload.php; calling it with require_once loads every class automatically, so you do not write manual require.
Exercise Print the config array
Define a $config array: name => "app/shop", require => ["monolog/monolog" => "^3.5", "guzzlehttp/guzzle" => "^7.8"], autoload => ["psr-4" => ["App\\" => "src/"]]. First print the name value, then each package under require in the form monolog/monolog: ^3.5, finally the App\ mapping under autoload psr-4 in the form App\ => src/.
Show example solution
" . $ver . "\n"; }. Print the mapping with foreach ($config["autoload"]["psr-4"] as $ns => $path) { echo $ns . " => " . $path . "\n"; }.
Example solution:
<?php
$config = [
"name" => "app/shop",
"require" => ["monolog/monolog" => "^3.5", "guzzlehttp/guzzle" => "^7.8"],
"autoload" => ["psr-4" => ["App\\" => "src/"]]
];
echo $config["name"] . "\n";
foreach ($config["require"] as $pkg => $ver) {
echo $pkg . ": " . $ver . "\n";
}
foreach ($config["autoload"]["psr-4"] as $ns => $path) {
echo $ns . " => " . $path . "\n";
}
Test yourself
-
Complete the require section
<?php
$config = [
"name" => "app/shop",
"____" => [
"monolog/monolog" => "^3.5"
]
];
echo $config["name"] . "\n";
Show answer
<?php
$config = [
"name" => "app/shop",
"require" => [
"monolog/monolog" => "^3.5"
]
];
echo $config["name"] . "\n";
-
What is the require-dev section for?
- It lists production packages
- It cleans the vendor/ folder
- It lists development-only packages
- It defines class paths
Show answer
It lists development-only packages — Correct. require-dev holds packages needed only during development.
-
Match the config sections
- name
- Holds the package name
- require
- Production packages
- require-dev
- Development packages
- autoload
- Sets up class loading
Next lesson: Adding packages with require