Skip to content

PHP Tutorial Namespaces and Autoloading

PSR-4 Autoloading Basics

Lesson 245 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

In the last lesson you wrote an autoloader that maps App\Service\Greeter to src/Service/Greeter.php. If every project invented its own mapping, sharing code would be a mess. PSR-4 is the agreed standard.

PSR stands for PHP Standards Recommendation. They come from the PHP-FIG group. PSR-4 describes how a fully qualified class name maps to a file path.

The rule

  1. A namespace prefix is mapped to a base folder.
  2. The rest of the class name is turned into a path: each \ becomes /, and .php is added.
PrefixBase folder
App\src/
ClassFile
App\Service\Greetersrc/Service/Greeter.php
App\Model\Usersrc/Model/User.php
App\Http\Controller\HomeControllersrc/Http/Controller/HomeController.php

What you must do

  • One class (or interface, trait, enum) per file.
  • The file name equals the type name exactly, including capitals.
  • The namespace in the file matches the folder path.

A file src/Service/Greeter.php must declare:

index.php
PHP
<?php

namespace App\Service;

class Greeter {}

A tiny PSR-4 autoloader

This shows how a PSR-4 mapper works.

index.php
PHP
<?php
function psr4Path(string $class, string $prefix, string $baseDir): ?string
{
    if (!str_starts_with($class, $prefix)) {
        return null;
    }

    $relative = substr($class, strlen($prefix));

    return rtrim($baseDir, "/") . "/" . str_replace("\\", "/", $relative) . ".php";
}

echo psr4Path("App\\Service\\Greeter", "App\\", "src") . "\n";
var_dump(psr4Path("Vendor\\Thing", "App\\", "src"));
Output
OUTPUT
src/Service/Greeter.php
NULL

Several mappings

A project can map several prefixes:

PrefixFolder
App\src/
Tests\tests/
Database\Seeders\database/seeders/

Why this standard matters

  • Every Composer package follows it, so installing a package “just works”.
  • Any tool or editor can find the file for a class name.
  • You can move between projects and know where things are.

Telling Composer

You do not write the autoloader. You describe the mapping in composer.json, and Composer generates the code.

data.json
JSON
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

The next chapter covers Composer, including this setting in PSR-4 Autoloading with Composer.

Other PSRs you will hear about

PSRTopic
PSR-1, PSR-12Coding style
PSR-3Logger interface
PSR-4Autoloading
PSR-7HTTP messages
PSR-11Container interface
PSR-15HTTP middleware

You do not need to memorise them. They show up when you use libraries and frameworks.

lightbulb
Case matters on Linux
Greeter.php and greeter.php are different files on Linux but the same on Windows. A project that works on your Windows laptop can fail on a Linux server if the capitals differ. Always match the class name exactly.