Programming languages · Beginner · 20 min
Manage PHP dependencies and autoloading with Composer
By Padding · Updated 18 Nov 2026
PHP 8.5.13 · Composer 2.11.3 · php:8.5-cli image (Debian 13) · Ubuntu 26.04
You will install Composer 2.11 with a checked installer, build a small PHP 8.5 basket library on a money package, autoload your own namespace with PSR-4, run PHPUnit 13 tests and PHPStan through Composer scripts, and audit and reinstall the dependencies from the lock file.
On this page
Almost every PHP project you will work on, from a Laravel app to a WordPress plugin with a build step, has a composer.json at its root. Composer is PHP's dependency manager. It reads the packages you ask for from that file, picks versions that fit together from Packagist (the public package registry), downloads them into a vendor/ folder and records the exact versions in composer.lock. It also writes an autoloader, one file you require once, after which PHP finds every class from your packages and from your own code without a single include line.
In this tutorial you build demo/basket, a small library that totals a shopping basket in any currency. Adding up prices with floats gives answers like 0.30000000000000004, so the library uses brick/money, which does exact decimal arithmetic and knows each currency's minor unit. You install Composer, start the project, add the library and two development tools, autoload your own src/ folder, run tests and static analysis through Composer scripts, audit the dependencies for known vulnerabilities and finally rebuild vendor/ from the lock file, the way a teammate or a deploy would.
Everything lives in ~/composer-demo, which you delete at the end. Composer itself stays installed.
Step 1 · Install the PHP extensions and Composer
PHPUnit needs PHP's XML and multibyte string extensions, and Composer unpacks downloaded packages with unzip. On Ubuntu 26.04, install them alongside the PHP CLI:
sudo apt update
sudo apt install -y php-cli php-xml php-mbstring unzip curlUbuntu also has a composer package, but it moves at Ubuntu's pace. The official installer gives you the current release. It is a PHP script, so before running it you compare its SHA-384 hash with the signature Composer publishes separately. If someone tampered with the download, the hashes differ and the script is deleted unrun:
cd ~
EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"
if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then echo "Installer checksum does not match"; rm composer-setup.php; false; fi
php composer-setup.php --version=2.11.3
rm composer-setup.php
sudo mv composer.phar /usr/local/bin/composer
composer --version--version=2.11.3 pins the release this tutorial was written against, so your output matches. Leave the flag off to get whatever is newest. The installer first prints All settings correct for using Composer, which means your PHP has everything Composer needs.
Composer in /usr/local/bin gets no updates from apt. When a new release comes out, update it in place with:
sudo composer self-updateOn macOS with Homebrew, brew install composer installs Composer instead, and brew upgrade keeps it current with the rest of your packages.
Check it worked
composer --version prints Composer version 2.11.3 with a release date, and on the next line the PHP version it runs on, PHP version 8.5. and a patch number. If the checksum line printed Installer checksum does not match, run the block again; if it fails twice, stop and check getcomposer.org/download for news before going further.
Step 2 · Start a library with composer init
Make the project folder and let Composer write the first composer.json. composer init normally asks questions one at a time; the flags answer them up front:
mkdir -p ~/composer-demo
cd ~/composer-demo
composer init --no-interaction \
--name demo/basket \
--description "Totals a shopping basket in any currency" \
--type library \
--license MIT \
--autoload src/
cat composer.jsonA package name is always vendor/project, lower case. The vendor part is usually your GitHub user or company name; demo is fine for practice. --autoload src/ is the important flag. It turns the package name into a namespace, Demo\Basket, and maps it to the src/ folder:
"autoload": {
"psr-4": {
"Demo\\Basket\\": "src/"
}
},That is a PSR-4 rule, the standard from the PHP Framework Interop Group that nearly every PHP package follows. It says: for a class whose full name starts with Demo\Basket\`, drop that prefix, turn the remaining backslashes into slashes, add `.php, and look in src/. So Demo\Basket\Basket lives in src/Basket.php, and Demo\Basket\Pricing\Tax would live in src/Pricing/Tax.php. The double backslashes are only JSON escaping.
Composer also creates src/ and generates vendor/autoload.php straight away. If your Git configuration has a name and email, they appear in an authors block. You may see Composer could not detect the root package (demo/basket) version, defaulting to '1.0.0'. Composer reads a package's own version from Git tags, and this folder has none. The warning is harmless, and you will see it again on several commands below.
Check it worked
cat composer.json shows "name": "demo/basket", the autoload block above and an empty "require": {}. The output of composer init ends with PSR-4 autoloading configured. Use "namespace Demo\Basket;" in src/, and ls shows composer.json, src and vendor.
Step 3 · Require a library and read the lock file
Add the PHP version you support and the money library. Each argument is package:constraint:
composer require php:^8.5 brick/money:^0.15.2Composer works out a set of versions that satisfy every constraint, downloads them, writes composer.lock, and finishes by checking them against known security advisories:
- Installing psr/simple-cache (3.0.0): Extracting archive
- Installing brick/math (1.0.0): Extracting archive
- Installing brick/money (0.15.2): Extracting archive
Generating autoload files
...
No security vulnerability advisories found.You asked for one package and got three. brick/money depends on brick/math and psr/simple-cache, and they come along. php is not downloaded: it is a platform requirement, a promise that this code needs PHP 8.5, which Composer checks against the PHP you run. Ask Composer what is installed and why:
composer show --tree
composer why brick/mathHow to read a constraint
The constraints in composer.json are ranges, not exact versions:
^1.4.2means at least 1.4.2 and below 2.0.0. The caret allows every release the author promises is backwards compatible under semantic versioning. Use it by default.- Before 1.0, the caret is stricter, because 0.x releases may break things in a minor version.
^0.15.2means at least 0.15.2 and below 0.16.0. That is why this tutorial pinsbrick/moneywith^0.15.2: version 0.16 could change its API, and you do not want it arriving unannounced. ~1.4means at least 1.4 and below 2.0, the same as^1.4. With three parts it narrows:~1.4.2means at least 1.4.2 and below 1.5.0, so only patch releases.||means "or". The tree showsbrick/moneyaccepting~0.15.0 || ~0.16.0 || ... || ^1.0ofbrick/math, a list of ranges its author has tested.
composer.json says what you will accept. composer.lock says exactly what you got. Open it in your editor: each entry under packages has a name, an exact version, the dist URL it was downloaded from with a checksum, and that package's own requirements. At the top, content-hash is a fingerprint of the requirement sections of composer.json, so Composer can tell when the two files have drifted apart.
Commit both files. A teammate, a CI job or a deploy runs composer install, which installs the exact versions in the lock file and never resolves anything afresh. Only composer update (or require) moves versions, and only within your constraints.
Check it worked
composer show --tree starts with brick/money 0.15.2 and shows brick/math and psr/simple-cache indented beneath it. composer why brick/math prints brick/money 0.15.2 requires brick/math (...). In composer.json the require block now reads "php": "^8.5" and "brick/money": "^0.15.2".
Step 4 · Write your own class and let the autoloader find it
Create the library class in src/Basket.php. Its namespace, Demo\Basket, plus its class name, Basket, matches the file path under the PSR-4 rule:
cat > src/Basket.php <<'PHP'
<?php
declare(strict_types=1);
namespace Demo\Basket;
use Brick\Money\Money;
final class Basket
{
/** @var list<array{name: string, price: Money, quantity: int}> */
private array $lines = [];
public function __construct(private readonly string $currency)
{
}
public function add(string $name, string $unitPrice, int $quantity = 1): self
{
if ($quantity < 1) {
throw new \InvalidArgumentException("Quantity for {$name} must be at least 1.");
}
$this->lines[] = [
'name' => $name,
'price' => Money::of($unitPrice, $this->currency),
'quantity' => $quantity,
];
return $this;
}
public function total(): Money
{
$total = Money::zero($this->currency);
foreach ($this->lines as $line) {
$total = $total->plus($line['price']->multipliedBy($line['quantity']));
}
return $total;
}
}
PHPPrices go in as strings such as '1450.50', never floats, so no precision is lost on the way in. Money::of refuses an amount with more decimal places than the currency has, so a typo like '1450.505' naira throws an exception instead of being rounded quietly.
Now a small script that uses it. The only line that loads code is require of vendor/autoload.php:
mkdir -p bin
cat > bin/demo.php <<'PHP'
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use Demo\Basket\Basket;
$basket = (new Basket('NGN'))
->add('Garri, 1 kg', '1450.50', 2)
->add('Palm oil, 1 litre', '3200');
echo $basket->total(), PHP_EOL;
PHP
php bin/demo.phpWhen PHP meets Demo\Basket\Basket it does not know the class, so it asks the autoloader, which applies the PSR-4 rule and includes src/Basket.php. When Basket uses Brick\Money\Money, the same thing happens with the rule brick/money declared in its own composer.json. Files load only when a class is first used.
You did not need to run anything after creating src/Basket.php. In development, the autoloader works out PSR-4 paths at run time, so new classes under an existing mapping are found straight away. You regenerate the autoloader when the mapping itself changes, which you do in the next step.
Check it worked
php bin/demo.php prints NGN 6101.00: two bags of garri at 1,450.50 plus one litre of palm oil at 3,200. If you see Class "Demo\Basket\Basket" not found, compare the namespace line and the file name with the PSR-4 rule; a capital letter out of place is enough to break it on Linux, where file names are case-sensitive.
Step 5 · Add development tools with require --dev
Some packages are for building the project, not for running it. Install PHPUnit 13 for tests and PHPStan 2.3 for static analysis as development requirements:
composer require --dev phpunit/phpunit:^13.4 phpstan/phpstan:^2.3They go into a separate require-dev block in composer.json. When someone installs your library as a dependency of their project, Composer never installs your require-dev packages, and a production deploy can leave them out too, as you will see later. PHPUnit alone pulls in a few dozen helper packages, which is exactly why you do not want it on a production server. Both tools put their commands in vendor/bin/:
vendor/bin/phpunit --version
vendor/bin/phpstan --versionCheck it worked
vendor/bin/phpunit --version prints PHPUnit 13.4. and a patch number, and vendor/bin/phpstan --version prints PHPStan - PHP Static Analysis Tool 2.3. and a patch number. composer.json now has "require-dev" with "phpunit/phpunit": "^13.4" and "phpstan/phpstan": "^2.3".
Step 6 · Autoload the tests and add Composer scripts
Tests get their own namespace, Demo\Basket\Tests, in a tests/ folder. They need an autoload rule too, but only during development, so it goes under autoload-dev. You will also add scripts, named commands that anyone on the project can run the same way.
Replace composer.json with the version below. The require and require-dev blocks are exactly what the commands above wrote, so the lock file stays in step; the new parts are autoload-dev, scripts and scripts-descriptions. If composer init added an authors block from your Git settings, paste it back in if you want to keep it.
cat > composer.json <<'JSON'
{
"name": "demo/basket",
"description": "Totals a shopping basket in any currency",
"type": "library",
"license": "MIT",
"require": {
"php": "^8.5",
"brick/money": "^0.15.2"
},
"require-dev": {
"phpunit/phpunit": "^13.4",
"phpstan/phpstan": "^2.3"
},
"autoload": {
"psr-4": {
"Demo\\Basket\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Demo\\Basket\\Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"lint": "phpstan analyse --level=8 --no-progress src tests bin",
"check": ["@lint", "@test"]
},
"scripts-descriptions": {
"test": "Run the PHPUnit tests",
"lint": "Analyse the code with PHPStan at level 8",
"check": "Run lint, then the tests"
}
}
JSON
composer validatecomposer validate checks the file's structure and confirms the lock file still matches it. Now look at the map the autoloader uses, which lives in vendor/composer/autoload_psr4.php:
grep Demo vendor/composer/autoload_psr4.phpOnly Demo\\Basket\\ is listed. The autoloader was generated before autoload-dev existed, and it does not reread composer.json on its own. Regenerate it:
composer dump-autoload
grep Demo vendor/composer/autoload_psr4.phpRun composer dump-autoload whenever you change an autoload or autoload-dev section by hand. composer require, install and update regenerate it for you.
Check it worked
composer validate prints ./composer.json is valid. If it instead says the lock file is not up to date, a constraint in your require blocks differs from what composer require wrote; compare them character by character. After dump-autoload, the grep shows two lines, one mapping Demo\\Basket\\Tests\\ to /tests and one mapping Demo\\Basket\\ to /src. composer run --list lists test, lint and check with their descriptions.
Step 7 · Write tests and run them with composer test
Give PHPUnit a configuration file, so phpunit with no arguments knows where the tests are and loads Composer's autoloader first:
cat > phpunit.xml <<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
cacheDirectory=".phpunit.cache"
colors="true">
<testsuites>
<testsuite name="unit">
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
XMLThen three tests: a total with quantities, an empty basket in Kenyan shillings, and a rejected quantity in Ghanaian cedis:
mkdir -p tests
cat > tests/BasketTest.php <<'PHP'
<?php
declare(strict_types=1);
namespace Demo\Basket\Tests;
use Demo\Basket\Basket;
use PHPUnit\Framework\TestCase;
final class BasketTest extends TestCase
{
public function testTotalMultipliesEachPriceByItsQuantity(): void
{
$basket = (new Basket('NGN'))
->add('Garri, 1 kg', '1450.50', 2)
->add('Palm oil, 1 litre', '3200');
self::assertSame('NGN 6101.00', (string) $basket->total());
}
public function testEmptyBasketTotalsZeroInItsCurrency(): void
{
$total = (new Basket('KES'))->total();
self::assertTrue($total->isZero());
self::assertSame('KES', $total->getCurrency()->getCurrencyCode());
}
public function testQuantityBelowOneIsRejected(): void
{
$this->expectException(\InvalidArgumentException::class);
(new Basket('GHS'))->add('Bread', '25', 0);
}
}
PHP
composer testcomposer test runs the test script. Inside a script, Composer puts vendor/bin at the front of PATH, so "phpunit" means this project's PHPUnit, not some other copy on your machine. Now run the analysis, then both together:
composer lint
composer check@lint and @test inside check refer to the other scripts, and Composer stops at the first one that fails. That one command is what you would run before every commit and in CI.
Check it worked
composer test ends with something like OK (3 tests, 4 assertions). composer lint prints [OK] No errors. composer check prints both, in that order. To see a failure, change 'NGN 6101.00' in the first test to 'NGN 6101.01' and run composer test again: PHPUnit reports FAILURES! with the two values side by side. Change it back before you go on.
Step 8 · Audit the dependencies for known vulnerabilities
Every require already ended with an advisory check. Run it on its own whenever you like, and in CI:
composer audit
composer audit --lockedcomposer audit checks the installed packages, including transitive ones such as brick/math, against the advisory database on Packagist. It also reports abandoned packages. --locked checks the versions in composer.lock instead of vendor/, so it works in a fresh checkout before anything is installed. The command exits with status 0 when nothing is found and 1 when something is, which is what makes it useful as a CI step.
Composer 2.11 also blocks known-vulnerable versions by default. If you require or update to a version with an active advisory, resolution fails and tells you which advisory blocked it, instead of installing it and warning afterwards. The policy section of the Composer configuration controls this, including ignoring a specific advisory with a written reason. Prefer upgrading the package; ignore an advisory only after you have read it and confirmed your code is not affected.
Check it worked
Both commands print No security vulnerability advisories found. and the shell prompt returns with no error. Run echo $? straight after composer audit and it prints 0.
Step 9 · Keep vendor out of Git and rebuild it from the lock file
vendor/ is generated, often large, and holds other people's code with its own history. Never commit it. Ignore it, along with PHPUnit's cache:
cat > .gitignore <<'TXT'
/vendor/
/.phpunit.cache/
TXTWhat you commit is composer.json, composer.lock, src/, tests/, bin/, phpunit.xml and .gitignore. To prove the lock file is enough, delete vendor/ and rebuild it the way a fresh clone would:
rm -rf vendor
composer install
composer testcomposer install prints Installing dependencies from lock file (including require-dev) and installs exactly the versions you had. Composer keeps every package it downloads in a local cache, so this reinstall barely touches the network. That matters if you pay for data by the gigabyte: on a prepaid mobile connection, a project rebuilt from cache costs almost nothing. See where the cache lives:
composer config cache-dirFor production, leave out the development tools and build an optimised autoloader. --optimize-autoloader (or -o) turns the PSR-4 rules into a class map, a single lookup table from class name to file, which saves file system checks on every request:
composer install --no-dev --optimize-autoloader
composer show
grep Basket vendor/composer/autoload_classmap.php
php bin/demo.phpThen put the development tools back for the rest of your work:
composer installCheck it worked
After the first composer install, composer test passes again. composer config cache-dir prints a path; on Ubuntu it is usually ~/.cache/composer, and on macOS ~/Library/Caches/composer. After --no-dev, composer show lists only brick/math, brick/money and psr/simple-cache, the class map contains 'Demo\\Basket\\Basket' => $baseDir . '/src/Basket.php', and php bin/demo.php still prints NGN 6101.00. The last composer install brings PHPUnit and PHPStan back.
Step 10 · Clean up
Delete the demo project. Composer stays in /usr/local/bin for your next project, and the package cache stays where cache-dir said:
cd ~
rm -rf ~/composer-demoIf you want Composer gone as well, sudo rm /usr/local/bin/composer removes it.
Check it worked
ls ~/composer-demo reports No such file or directory, and composer --version still prints Composer version 2.11.3.
Next steps
- See what PHP 8.5 adds to the language your library is written in: use the new features in PHP 8.5.
- Turn up the safety of the code itself with strict types, enums and readonly classes: write safer PHP.
- Compare Composer with how another language does it, with no separate install step: manage Go dependencies with modules.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials