Thuta Learning
PHP
AdvancedProgrammingBeginner

Namespaces, Composer & Autoloading

PHPLesson 2235 min

What you'll walk away with

  • Declare a namespace and use use, aliases and fully qualified names such as \DateTime correctly
  • Understand that use only links a name and never loads a file, and fix class-not-found errors
  • Write a PSR-4 style autoloader yourself with spl_autoload_register, mapping a prefix to a directory
  • Read the require and autoload parts of composer.json and say when to use install, update and dump-autoload

Explain it simply

Namespaces and Composer in plain language

A namespace is a surname for names. Two people called Ada are only told apart by their family names, and two classes called Logger stop colliding once they are App\Logging\Logger and Vendor\Monolog\Logger.

Composer is the package manager that downloads the libraries your project needs and also generates an autoloader that finds and loads class files for you when they are first used. That means you no longer write a require line for every class.

Problem → Why → Solution

The problem: duplicate names and a wall of require lines

As a project grows, your own User class collides with a library that also declares a class called User. PHP allows each class name only once, so you get the fatal error 'Cannot declare class User, because the name is already in use'. The second problem is the files: with fifty classes, the top of index.php needs fifty require_once lines, and forgetting to add one when you create a class gives Class not found.

The third problem is downloading libraries by hand and copying them into the project folder. Nobody can say which version is installed, how to update it, or which library depends on which.

index.php
<?php
require_once 'src/User.php';
require_once 'src/Order.php';
require_once 'src/Invoice.php';
// ... forty-seven more lines, one per class ...
require_once 'lib/some-library/src/User.php';   // declares another class User

$user = new User('Ada');   // Fatal error: Cannot declare class User

Why three separate tools solve it

Namespaces solve the name collision, autoloading solves the file hunting, and Composer solves library management. Each does a separate job but they work best together: namespaces give a rule that turns a class name into a file path, the autoloader follows that rule to load the file, and Composer writes the autoloader for you.

Core concept: name, path and autoloader

A namespace is part of the class name. Write namespace App\Models; at the top of a file and every class, interface, trait, enum, function and const declared below lives in App\Models, so the full name of the User class is App\Models\User. The namespace declaration must be the first statement in the file (after an optional declare), or PHP stops with a fatal error.

Full names are long, so you import them with use: after use App\Models\User; you can write just User, use App\Support\Slug as SlugHelper; renames on import, and use function and use const exist for functions and constants. The key point is that use is only a compile-time alias and never loads a file. Inside a namespaced file, an unqualified class name is looked up in the current namespace first, so new DateTime() inside namespace Shop\Billing; looks for Shop\Billing\DateTime and fails; write \DateTime or add use DateTime;. Functions and constants are more forgiving: if they are not found in the current namespace PHP falls back to the global one, so strlen() works without a backslash.

So who loads the file? spl_autoload_register registers a function that PHP calls when it meets a class name it does not know. PSR-4 gives that function a rule: a namespace prefix maps to a base directory, and the rest of the class name becomes subdirectories and the file name. With App\ pointing at src/, App\Models\User becomes src/Models/User.php. Keep one class per file and match the file name to the class name exactly, because Linux is case-sensitive.

Composer is PHP's dependency manager. composer.json lists what the project needs (require) and its autoload map; composer install puts the exact versions from composer.lock into vendor/ and generates vendor/autoload.php. One line at the top of the entry file, require __DIR__ . '/vendor/autoload.php';, makes classes from your own src/ and from every library loadable. A constraint like ^2.1 means any 2.x version from 2.1 upward but not 3.0, and composer.lock records the exact versions that were actually chosen.

Turning a class name into a file path
  1. Code asks for App\Models\User
  2. Unknown class: ask the autoloader
  3. Drop the prefix, turn \ into /
  4. require src/Models/User.php

use only links a name and triggers nothing; autoloading happens when the class is actually used.

General pattern

php
<?php
namespace Vendor\Package\Sub;          // first statement in the file

use Other\Package\SomeClass;            // import a name, loads nothing
use Other\Package\Long\Name as Short;   // import under another name
use function Other\Package\helper;      // import a function

final class ClassName { }               // file: src/Sub/ClassName.php

Declare the namespace at the very top of the file and group the use lines beneath it. When the class name matches the file name, a PSR-4 autoloader finds the file directly.

Worked example: writing a PSR-4 autoloader by hand

Writing by hand what Composer generates for you is the clearest way to see what is going on. This sample creates src/Models/User.php and src/Support/Slug.php in a temporary directory and registers an autoloader that follows the PSR-4 rule. The autoloader prints a line every time it is called, so you can see exactly when each class gets loaded. Composer is not involved at all.

psr4-demo.php
<?php
use App\Models\User;
use App\Support\Slug as SlugHelper;

$root = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'psr4_' . bin2hex(random_bytes(4));
mkdir($root . '/src/Models', 0777, true);
mkdir($root . '/src/Support', 0777, true);

file_put_contents($root . '/src/Models/User.php', <<<'FILE'
<?php
namespace App\Models;

use App\Support\Slug;

final class User
{
    public function __construct(public readonly string $name)
    {
    }

    public function handle(): string
    {
        return Slug::make($this->name);
    }
}
FILE);

file_put_contents($root . '/src/Support/Slug.php', <<<'FILE'
<?php
namespace App\Support;

final class Slug
{
    public static function make(string $text): string
    {
        return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($text)), '-');
    }
}
FILE);

spl_autoload_register(function (string $class) use ($root): void {
    $prefix = 'App\\';
    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }
    $relative = substr($class, strlen($prefix));
    $file = $root . '/src/' . str_replace('\\', '/', $relative) . '.php';
    echo "autoload request: $class\n";
    if (is_file($file)) {
        require $file;
    }
});

echo "autoloader registered, nothing loaded yet\n";
echo 'User loaded already? ', var_export(class_exists(User::class, false), true), "\n";

$user = new User('Ada Lovelace');
echo 'created: ', get_class($user), "\n";

$handle = $user->handle();
echo 'handle: ', $handle, "\n";
echo 'alias: ', SlugHelper::make('  Hello,  PHP World!  '), "\n";

$exists = class_exists('App\Missing\Thing');
echo 'unknown class exists? ', var_export($exists, true), "\n";

unlink($root . '/src/Models/User.php');
unlink($root . '/src/Support/Slug.php');
rmdir($root . '/src/Models');
rmdir($root . '/src/Support');
rmdir($root . '/src');
rmdir($root);

Code breakdown

  1. Import names, load nothinguse App\Models\User;

    This line only links the name User to App\Models\User. Nothing fails even though no file exists yet, because nothing is loaded.

  2. Files in a nowdocnamespace App\Models;

    Text inside a nowdoc (<<<'FILE') is kept exactly as written, so backslashes and $ need no escaping. This line declares the file's namespace, matching the fact that the file lives under src/Models/.

  3. Skip foreign classesif (strncmp($class, $prefix, strlen($prefix)) !== 0) {

    The autoloader leaves classes that do not start with 'App\' alone, which lets other autoloaders, such as a library's, do their own job.

  4. Map the name to a path$file = $root . '/src/' . str_replace('\\', '/', $relative) . '.php';

    After the prefix is cut off, the remaining Models\User has its \ turned into / and .php added, giving Models/User.php. That is the whole PSR-4 rule in one line.

  5. Load on first use$user = new User('Ada Lovelace');

    Only when this line runs is the autoloader called and User.php loaded. The Slug class used inside User::handle() is autoloaded in turn the first time it is needed.

You should see
autoloader registered, nothing loaded yet
User loaded already? false
autoload request: App\Models\User
created: App\Models\User
autoload request: App\Support\Slug
handle: ada-lovelace
alias: hello-php-world
autoload request: App\Missing\Thing
unknown class exists? false

Understanding use, aliases and the global namespace

The file below lives in the Shop\Billing namespace. ::class gives the full name at compile time, and it substitutes the alias too. You can also see what happens when DateTime is used without a use line: PHP looks for Shop\Billing\DateTime.

namespace-resolution.php
<?php
namespace Shop\Billing;

use DateTimeImmutable;
use InvalidArgumentException as BadInput;

final class Invoice
{
    public function __construct(public readonly string $number)
    {
    }
}

echo __NAMESPACE__, "\n";
echo Invoice::class, "\n";
echo strtoupper('functions fall back to global'), "\n";
echo \strlen('abc'), "\n";

try {
    $when = new DateTime('2026-01-01');
} catch (\Error $e) {
    echo $e->getMessage(), "\n";
}

$when = new DateTimeImmutable('2026-03-15');
echo get_class($when), "\n";
echo BadInput::class, "\n";
text
Shop\Billing
Shop\Billing\Invoice
FUNCTIONS FALL BACK TO GLOBAL
3
Class "Shop\Billing\DateTime" not found
DateTimeImmutable
InvalidArgumentException

Seeing the PSR-4 mapping

The PSR-4 rule has only three steps: cut the prefix, turn \ into /, add .php. That means a class name tells you where its file is, and a file's location tells you what its namespace must be.

text
PSR-4 mapping with "App\\": "src/"
----------------------------------
Class name                         File on disk
--------------------------------   --------------------------------
App\Models\User              -->   src/Models/User.php
App\Support\Slug             -->   src/Support/Slug.php
App\Http\Controllers\Home    -->   src/Http/Controllers/Home.php

rule: cut the prefix "App\", turn "\" into "/", append ".php"

Composer day to day

Composer cannot run inside this lesson, so this part is for commands you try on your own machine once Composer is installed. The require section of composer.json limits libraries and your PHP version, and autoload.psr-4 links your own namespace to a directory.

composer.json
{
  "name": "acme/tea-shop",
  "require": {
    "php": "^8.2",
    "monolog/monolog": "^3.0"
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}
bash
composer init                     # create composer.json step by step
composer require monolog/monolog   # add a library, update json + lock, install it
composer install                   # install exactly what composer.lock says
composer update                    # pick the newest allowed versions, rewrite the lock
composer dump-autoload             # rebuild the autoloader after editing "autoload"
CommandWhen to use it
composer installon servers, CI and a new teammate's machine, when you want the exact locked versions
composer updatein development, when you deliberately want newer library versions
composer requirewhen adding a new dependency
composer dump-autoloadafter you change the autoload map

On production use composer install --no-dev --optimize-autoloader and avoid composer update, because versions can change unexpectedly. Commit composer.json and composer.lock to git but not vendor/, which can be rebuilt from the lock at any time.

In real projects

Namespaces and Composer in real projects

Almost every package in the PHP ecosystem is installed with Composer from Packagist. Frameworks such as Laravel and Symfony keep your code under an App\ namespace and are built on PSR-4 autoloading. Common libraries for logging (Monolog), HTTP requests (Guzzle) and testing (PHPUnit) arrive with one composer require and are then used alongside your own classes.

In a team, composer.lock guarantees that every developer and the production server run the same versions, which removes many 'it works on my machine' problems. Your own code can also be split into a package and reused in other projects.

  • CI pipelines run composer install as a build step and run the tests against that vendor/ folder.
  • Docker images run composer install --no-dev at build time, so the production container already contains vendor/.
  • Onboarding: a new teammate clones the repository and gets going with a single composer install.

Common mistakes

Common mistakes with namespaces and Composer

Thinking use loads the file

With use App\Models\User; but no autoloader, new User() still gives Class not found. use only links the name; loading is the autoloader's job.

Forgetting the backslash for global classes

new DateTime() inside a namespace Shop\Billing; file fails with Class "Shop\Billing\DateTime" not found. Write \DateTime or add use DateTime; at the top of the file.

Letting directory and file name case drift

Naming the file src/models/user.php for App\Models\User works on Windows and breaks on a Linux server. Keep namespace, directory and file name identical in case.

Editing the autoload map without dump-autoload

After adding a new prefix to composer.json, Composer does not know about it until you run composer dump-autoload, so those classes stay unfound.

Running composer update on production

composer update can rewrite the locked versions, so untested versions may reach production. Commit composer.lock and use only composer install on the server.

Best practices

Best practices

  • Keep one class per file and give the file exactly the class's name.
  • Make namespaces mirror the directory structure (App\Models maps to src/Models).
  • Group use lines at the top of the file and remove imports you no longer use.
  • Commit composer.json and composer.lock but not vendor/, and use only composer install on the server.

Mini challenge

Mini challenge: your own autoloader factory

Write makeAutoloader(string $prefix, string $baseDir): callable. It returns a function that maps only classes starting with the prefix to files under baseDir following the PSR-4 rule. Create an Acme\Tools\Greeter class file in a temp directory to test it, and show that the autoloader ignores an unrelated class.

  • The autoloader returns without doing anything for a class name that does not start with the prefix
  • It cuts the prefix, turns \ into /, appends .php and joins the result to baseDir
  • It requires the file only if it exists (is_file)
  • Create lib/Tools/Greeter.php in a temp directory, use Greeter and print a message, probe Other\Thing with class_exists, and delete the files afterwards
autoloader-factory.php
<?php
function makeAutoloader(string $prefix, string $baseDir): callable
{
    return function (string $class) use ($prefix, $baseDir): void {
        // TODO: ignore classes that do not start with $prefix
        // TODO: cut the prefix and turn namespace separators into directory separators
        // TODO: require the file only when it exists
    };
}

$root = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'lib_' . bin2hex(random_bytes(4));
// TODO: create $root/Tools/Greeter.php (namespace Acme\Tools, class Greeter::greet())

// TODO: register makeAutoloader('Acme\\', $root) with spl_autoload_register
// TODO: print Greeter's greeting, then check class_exists('Other\Thing')
// TODO: delete the created files and directories

Expected: Greeter's message prints as 'Hello, Ada! (from Acme\Tools\Greeter)', and Other\Thing is reported as not found (false).

Show hint

Cut the prefix with substr($class, strlen($prefix)) and swap separators with str_replace('\\', '/', ...). Writing the temp file with a nowdoc means the backslashes need no escaping.

Show solution
autoloader-factory.php
<?php
function makeAutoloader(string $prefix, string $baseDir): callable
{
    return function (string $class) use ($prefix, $baseDir): void {
        if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
            return;
        }
        $relative = substr($class, strlen($prefix));
        $file = $baseDir . '/' . str_replace('\\', '/', $relative) . '.php';
        if (is_file($file)) {
            require $file;
        }
    };
}

$root = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'lib_' . bin2hex(random_bytes(4));
mkdir($root . '/Tools', 0777, true);
file_put_contents($root . '/Tools/Greeter.php', <<<'FILE'
<?php
namespace Acme\Tools;

final class Greeter
{
    public function greet(string $name): string
    {
        return "Hello, $name! (from " . self::class . ')';
    }
}
FILE);

spl_autoload_register(makeAutoloader('Acme\\', $root));

$greeter = new Acme\Tools\Greeter();
echo $greeter->greet('Ada'), "\n";
echo 'Other\Thing found? ', var_export(class_exists('Other\Thing'), true), "\n";

unlink($root . '/Tools/Greeter.php');
rmdir($root . '/Tools');
rmdir($root);

Quick quiz 1 / 3

composer.json contains "App\\": "src/". Which file is searched for App\Http\Controllers\HomeController?

Quick quiz 2 / 3

A file starts with use App\Models\User; and the autoloader cannot find that class's file. When does the error appear?

Quick quiz 3 / 3

Which command belongs in a production deployment of a project that has a committed composer.lock?

What to remember

  • Namespaces group class names to avoid collisions, and use only links a name without loading the file.
  • A global class inside a namespace needs a leading backslash or a use line, while functions fall back to the global scope.
  • A PSR-4 autoloader cuts the prefix, turns \ into / and appends .php, and spl_autoload_register stores that function.
  • Composer reads require and autoload and generates vendor/autoload.php; use install on servers and update or dump-autoload in development.

Composer Basic Usage and Autoloading — Composer

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.