What is Composer and why does PHP need it?

Short answer

Composer installs PHP libraries and generates an autoloader so classes load on demand. Run composer require vendor/package, then require "vendor/autoload.php" once.

#Getting started

bash
composer init            # creates composer.json
composer require monolog/monolog
composer install         # installs what composer.lock specifies

Then, once, at the top of your entry point:

php
require __DIR__ . '/vendor/autoload.php';

Every installed class is now available. No more require per file.

#Autoloading your own code

In composer.json:

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

Run composer dump-autoload. Now App\\Models\\User loads from src/Models/User.php automatically — the namespace mirrors the directory structure.

#composer.json vs composer.lock

composer.json records what you asked for, usually as a range like ^3.0.

composer.lock records the exact versions installed.

Commit both. composer install reads the lock file, so every machine gets identical versions; composer update re-resolves the ranges and rewrites the lock.

#Do not commit vendor/

Add it to .gitignore. It is rebuilt from the lock file, it is large, and it can contain platform-specific binaries.

#Optimise for production

bash
composer install --no-dev --optimize-autoloader

--no-dev skips test-only packages; --optimize-autoloader builds a static class map instead of checking the filesystem on each load.