PHPPHP
IntermediateLesson 13 of 16

Composer, Namespaces & Autoloading – PHP

Installing packages and organizing your own code cleanly into namespaces.

Composer is the package manager of PHP (the counterpart of npm/pip). Packages come from Packagist. Composer places them in vendor/ and generates an autoloader that loads classes on demand.

composer init
composer require monolog/monolog
composer require --dev phpunit/phpunit
composer install          # installs exactly the versions from composer.lock
composer update           # updates within the allowed range
composer dump-autoload    # regenerate the autoloader

The file composer.json describes dependencies and autoloading. PSR-4 maps a namespace prefix to a folder:

{
    "name": "mycompany/shop",
    "require": {
        "php": ">=8.2",
        "monolog/monolog": "^3.0"
    },
    "require-dev": { "phpunit/phpunit": "^11.0" },
    "autoload": {
        "psr-4": { "App\\": "src/" }
    }
}
<?php
// src/Service/Rechner.php
declare(strict_types=1);

namespace App\Service;

final class Rechner {
    public function addiere(int $a, int $b): int {
        return $a + $b;
    }
}
<?php
// index.php
declare(strict_types=1);

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

use App\Service\Rechner;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger("app");
$log->pushHandler(new StreamHandler(__DIR__ . "/app.log"));
$log->info("Start");

echo (new Rechner())->addiere(2, 3);   // 5
Tip^3.0 allows all 3.x versions (semantic versioning). Commit composer.lock to the repository (reproducible builds), but not the vendor/ folder.
WarningA namespace name must match the path: AppServiceRechner lives in src/Service/Rechner.php – including upper/lower case. On Linux servers the file name is case-sensitive, on Windows/macOS it is not.