Composer and Packages

PHP Autoloading and PSR-4 with Composer

Learn why autoloading matters and how to map PHP namespaces to directories with Composer PSR-4 configuration.

PHP Autoloading and PSR-4 with Composer

Autoloading lets PHP load class files when they are needed, without requiring every file manually. Composer generates an autoloader that supports common PHP autoloading standards.

Configure PSR-4

A project's composer.json can map a namespace prefix to a source directory.

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

With this mapping, a class named App\\Services\\Mailer is expected in src/Services/Mailer.php, following the namespace and directory structure.

Generate the Autoloader

After changing autoload configuration, run:

composer dump-autoload

Then include Composer's generated autoloader once in the application entry point.

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

$mailer = new App\Services\Mailer();

Namespace and File Organization

The namespace declaration inside the class file should match the mapping.

<?php
namespace App\Services;

class Mailer
{
    public function send(): void
    {
        // Send a message through the configured mail service.
    }
}

Class names and file names should follow consistent capitalization. This is particularly important on case-sensitive production file systems.

Practical Guidelines

Keep application source code separate from third-party dependencies, avoid editing files inside vendor/, and regenerate the autoloader after configuration changes. Use Composer's optimized autoloader for production deployments when appropriate.

Conclusion

PSR-4 provides a predictable relationship between namespaces and file paths. Combined with Composer's autoloader, it helps PHP projects stay organized as the codebase grows.

Share this page Help other developers discover this resource.