Skip to main content

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:

Bash
sudo apt update
sudo apt install -y php-cli php-xml php-mbstring unzip curl

Ubuntu 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:

Bash
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:

Bash
sudo composer self-update

On 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:

Bash
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.json

A 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:

JSON
"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:

Bash
composer require php:^8.5 brick/money:^0.15.2

Composer works out a set of versions that satisfy every constraint, downloads them, writes composer.lock, and finishes by checking them against known security advisories:

Text
  - 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:

Bash
composer show --tree
composer why brick/math

How to read a constraint

The constraints in composer.json are ranges, not exact versions:

  • ^1.4.2 means 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.2 means at least 0.15.2 and below 0.16.0. That is why this tutorial pins brick/money with ^0.15.2: version 0.16 could change its API, and you do not want it arriving unannounced.
  • ~1.4 means at least 1.4 and below 2.0, the same as ^1.4. With three parts it narrows: ~1.4.2 means at least 1.4.2 and below 1.5.0, so only patch releases.
  • || means "or". The tree shows brick/money accepting ~0.15.0 || ~0.16.0 || ... || ^1.0 of brick/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:

Bash
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;
    }
}
PHP

Prices 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:

Bash
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.php

When 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:

Bash
composer require --dev phpunit/phpunit:^13.4 phpstan/phpstan:^2.3

They 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/:

Bash
vendor/bin/phpunit --version
vendor/bin/phpstan --version

Check 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.

Bash
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 validate

composer 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:

Bash
grep Demo vendor/composer/autoload_psr4.php

Only Demo\\Basket\\ is listed. The autoloader was generated before autoload-dev existed, and it does not reread composer.json on its own. Regenerate it:

Bash
composer dump-autoload
grep Demo vendor/composer/autoload_psr4.php

Run 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:

Bash
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>
XML

Then three tests: a total with quantities, an empty basket in Kenyan shillings, and a rejected quantity in Ghanaian cedis:

Bash
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 test

composer 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:

Bash
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:

Bash
composer audit
composer audit --locked

composer 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:

Bash
cat > .gitignore <<'TXT'
/vendor/
/.phpunit.cache/
TXT

What 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:

Bash
rm -rf vendor
composer install
composer test

composer 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:

Bash
composer config cache-dir

For 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:

Bash
composer install --no-dev --optimize-autoloader
composer show
grep Basket vendor/composer/autoload_classmap.php
php bin/demo.php

Then put the development tools back for the rest of your work:

Bash
composer install

Check 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:

Bash
cd ~
rm -rf ~/composer-demo

If 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

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.