Bird
Raised Fist0
PHPprogramming~10 mins

PSR-4 directory mapping in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - PSR-4 directory mapping
Namespace Prefix
↓
Map to Base Directory
↓
Class Name
↓
Remove Prefix from Class
↓
Replace Namespace Separators with Directory Separators
↓
Append .php Extension
↓
Load File from Mapped Directory
PSR-4 maps a namespace prefix to a base directory. Class names are converted to file paths by removing the prefix, replacing namespace separators with directory separators, and adding .php.
Execution Sample
PHP
<?php
spl_autoload_register(function ($class) {
    $prefix = "App\\";
    $base_dir = __DIR__ . "/src/";
    if (str_starts_with($class, $prefix)) {
        $relative_class = substr($class, strlen($prefix));
        $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
        if (file_exists($file)) {
            require $file;
        }
    }
});
This code registers an autoloader that loads classes in the 'App\' namespace from the 'src/' directory by converting namespace to file path.
Execution Table
StepInput ClassCheck PrefixRelative ClassFile PathFile Exists?Action
1App\Controller\HomeControllerYes (starts with 'App\\')Controller\HomeController/path/src/Controller/HomeController.phpYesRequire file
2App\Model\UserYes (starts with 'App\\')Model\User/path/src/Model/User.phpNoDo nothing
3Other\ServiceNo (does not start with 'App\\')---Do nothing
💡 Stop after checking prefix and file existence for each class.
Variable Tracker
VariableStartAfter 1After 2After 3
$class-App\Controller\HomeControllerApp\Model\UserOther\Service
$prefixApp\\App\\App\\App\\
$base_dir/path/src//path/src//path/src//path/src/
$relative_class-Controller\HomeControllerModel\User-
$file-/path/src/Controller/HomeController.php/path/src/Model/User.php-
Key Moments - 3 Insights
Why do we remove the namespace prefix from the class name before building the file path?
Because the base directory already corresponds to the namespace prefix, so removing it avoids repeating the prefix in the file path. See execution_table rows 1 and 2 where $relative_class excludes the prefix.
What happens if the class does not start with the namespace prefix?
The autoloader ignores it and does not try to load a file. See execution_table row 3 where prefix check fails and no file is loaded.
Why do we replace backslashes '\\' with slashes '/' in the relative class name?
Because namespaces use backslashes but file paths use directory separators (slashes). This conversion creates the correct file path. See execution_table rows 1 and 2 for file path construction.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the file path for the class 'App\\Model\\User'?
A/path/src/User.php
B/path/src/App/Model/User.php
C/path/src/Model/User.php
D/path/Model/User.php
💡 Hint
Check the 'File Path' column in execution_table row 2.
At which step does the autoloader decide not to load any file because the prefix does not match?
AStep 1
BStep 3
CStep 2
DNone
💡 Hint
Look at the 'Check Prefix' column in execution_table row 3.
If the base directory was changed to '/app/src/', how would the file path for 'App\\Controller\\HomeController' change?
A/app/src/Controller/HomeController.php
B/path/src/Controller/HomeController.php
C/app/Controller/HomeController.php
D/src/Controller/HomeController.php
💡 Hint
Refer to variable_tracker row for $base_dir and how it affects $file.
Concept Snapshot
PSR-4 maps a namespace prefix to a base directory.
Remove the prefix from the full class name.
Replace namespace separators '\\' with directory separators '/'.
Append '.php' to get the file path.
Load the file from the base directory.
This enables automatic class loading by namespace.
Full Transcript
PSR-4 directory mapping works by linking a namespace prefix to a base directory. When a class is requested, the autoloader checks if the class name starts with the prefix. If yes, it removes the prefix from the class name to get the relative class. Then it replaces namespace backslashes with directory slashes and adds '.php' to form the file path inside the base directory. If the file exists, it is loaded. If the prefix does not match or the file is missing, the autoloader does nothing. This process allows PHP to automatically find and load class files based on their namespaces and directory structure.

Practice

(1/5)
1. What is the main purpose of PSR-4 in PHP?
PSR-4 helps with:
easy
A. Mapping namespaces to directory paths for autoloading classes
B. Defining coding style rules for PHP files
C. Encrypting PHP source code for security
D. Managing database connections automatically

Solution

  1. Step 1: Understand PSR-4 role

    PSR-4 is a standard that maps PHP namespaces to folder paths to load classes automatically.
  2. Step 2: Compare options

    Only Mapping namespaces to directory paths for autoloading classes describes this mapping and autoloading purpose correctly.
  3. Final Answer:

    Mapping namespaces to directory paths for autoloading classes -> Option A
  4. Quick Check:

    PSR-4 = Namespace to folder mapping [OK]
Hint: PSR-4 links namespaces to folders for autoloading [OK]
Common Mistakes:
  • Confusing PSR-4 with coding style rules
  • Thinking PSR-4 encrypts code
  • Assuming PSR-4 manages databases
2. Which of the following is the correct way to define a PSR-4 autoload entry in composer.json?
easy
A. "autoload": { "psr-4": { "App": "src" } }
B. "autoload": { "psr-4": { "App/": "src\\" } }
C. "autoload": { "psr-4": { "App\\": "src/" } }
D. "autoload": { "psr-4": { "App\\": "src\\" } }

Solution

  1. Step 1: Check PSR-4 syntax in composer.json

    PSR-4 keys use double backslashes for namespace separator and forward slashes for folder paths.
  2. Step 2: Validate each option

    "autoload": { "psr-4": { "App\\": "src/" } } correctly uses "App\\" for namespace and "src/" for directory path.
  3. Final Answer:

    "autoload": { "psr-4": { "App\\": "src/" } } -> Option C
  4. Quick Check:

    Namespace ends with \\ and folder path uses / [OK]
Hint: Use double backslashes for namespaces, forward slashes for folders [OK]
Common Mistakes:
  • Using single backslash in JSON string
  • Mixing slashes in folder paths
  • Omitting trailing backslash in namespace
3. Given this composer.json snippet:
{
  "autoload": {
    "psr-4": {
      "MyApp\\": "app/"
    }
  }
}

Where should the class MyApp\Controllers\HomeController be located?
medium
A. app/Controllers/HomeController.class.php
B. app/MyApp/Controllers/HomeController.php
C. src/Controllers/HomeController.php
D. app/Controllers/HomeController.php

Solution

  1. Step 1: Understand PSR-4 mapping

    The namespace prefix "MyApp\\" maps to folder "app/". The rest of the namespace after prefix maps to subfolders.
  2. Step 2: Map class namespace to file path

    Class "MyApp\\Controllers\\HomeController" maps to "app/Controllers/HomeController.php".
  3. Final Answer:

    app/Controllers/HomeController.php -> Option D
  4. Quick Check:

    Namespace after prefix = Controllers/HomeController.php [OK]
Hint: Namespace after prefix = folder path + class name.php [OK]
Common Mistakes:
  • Adding namespace prefix folder again
  • Using wrong base folder like src/
  • Wrong file extension
4. You have this composer.json autoload section:
{
  "autoload": {
    "psr-4": {
      "Lib\\": "lib/"
    }
  }
}

But when you try to use Lib\Utils\Helper, PHP cannot find the class. What is the likely problem?
medium
A. Composer dump-autoload was not run after adding the class
B. The class file is not located at lib/Utils/Helper.php
C. The namespace prefix "Lib\\" should not have trailing backslash
D. The folder path should be "lib\\" with double backslashes

Solution

  1. Step 1: Check common PSR-4 issues

    Folder path uses forward slashes, trailing backslash in namespace prefix is correct, so options C and D are wrong.
  2. Step 2: Verify autoload update

    After adding new classes, you must run composer dump-autoload to update the autoloader.
  3. Final Answer:

    Composer dump-autoload was not run after adding the class -> Option A
  4. Quick Check:

    Run dump-autoload after changes [OK]
Hint: Always run composer dump-autoload after adding classes [OK]
Common Mistakes:
  • Changing folder slashes incorrectly
  • Removing trailing backslash in namespace prefix
  • Forgetting to update autoloader
5. You want to autoload two separate namespaces in your project:
"App\\": "src/", "Vendor\\Package\\": "vendor/package/src/"
Which composer.json snippet correctly sets this up?
hard
A. "autoload": { "psr-4": { "App/": "src/", "Vendor/Package/": "vendor/package/src/" } }
B. "autoload": { "psr-4": { "App\\": "src/", "Vendor\\Package\\": "vendor/package/src/" } }
C. "autoload": { "psr-4": { "App\\": "src/", "Vendor\\Package": "vendor/package/src" } }
D. "autoload": { "psr-4": { "App": "src", "Vendor\\Package\\": "vendor/package/src/" } }

Solution

  1. Step 1: Check namespace keys format

    Namespace keys must end with double backslashes to separate namespaces properly.
  2. Step 2: Check folder paths format

    Folder paths use forward slashes and end with a slash for directories.
  3. Step 3: Validate each option

    "autoload": { "psr-4": { "App\\": "src/", "Vendor\\Package\\": "vendor/package/src/" } } correctly uses double backslashes for both namespaces and trailing slashes for folders.
  4. Final Answer:

    "autoload": { "psr-4": { "App\\": "src/", "Vendor\\Package\\": "vendor/package/src/" } } -> Option B
  5. Quick Check:

    Double backslashes + trailing slash folder paths [OK]
Hint: Use double backslashes for namespaces and trailing slash for folders [OK]
Common Mistakes:
  • Omitting trailing backslash in namespace keys
  • Using forward slashes in namespace keys
  • Missing trailing slash in folder paths
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard