composer and ecosystem

Composer Autoloading

Composer autoloading lets PHP load classes without manual require statements. PSR-4 mappings connect namespace prefixes to source directories and keep application structure predictable.

Working Knowledge

  • Map application namespaces under autoload.psr-4.
  • Keep namespace and directory casing consistent.
  • Run composer dump-autoload after changing mappings.
  • Use autoload-dev for test fixtures and test namespaces.
  • Avoid manual file includes for normal namespaced classes.

Map A Namespace With PSR-4

{
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\\": "tests/"
    }
  }
}

With this mapping, App\Billing\Invoice belongs in:

src/Billing/Invoice.php

The namespace, directory names, and filename casing must match. A mismatch can work on a case-insensitive laptop and fail on Linux in CI or production.

Load Composer's Autoloader

An entry script loads the generated autoloader once:

PHP example
<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';

Normal application classes should not need scattered manual require statements after that.

Debug Class-Not-Found Errors

Check the class namespace, directory path, filename case, mapping, and whether dependencies were installed. After changing mappings, regenerate autoload files:

composer dump-autoload

For an optimized production autoloader, follow the deployment command already used by the project.

In Application Work

When a class cannot be found, inspect its namespace, path, case, Composer mapping, and generated autoloader before adding workaround includes.

What To Check

Before moving on, make sure you can map a namespace to a directory, locate a class file from its full name, load Composer's autoloader, and diagnose casing and mapping errors.

Practice

Practice: Diagnose An Autoload Failure

Break the App\Support\Slugger example deliberately by changing either the namespace or filename case. Run the loading check, diagnose the failure, and restore the correct mapping.

Requirements

  • Check namespace-to-directory mapping.
  • Check filename and case.
  • Regenerate autoload files.
  • Keep test namespaces in autoload-dev.

Record the failing class name, expected source path, actual source path, and repair command.

Show solution

Check the namespace, class name, path, and filename casing first. Then compare the application namespace with autoload.psr-4 in composer.json.

Run composer dump-autoload after changing the mapping. Keep test-only namespaces under autoload-dev, and avoid manual require calls for ordinary namespaced classes.

For App\Support\Slugger, the expected path under the lesson mapping is src/Support/Slugger.php. A lowercase filename may work locally on a case-insensitive filesystem and fail on Linux.