PSR-4 directory mapping helps PHP find your classes automatically by linking namespaces to folders. This makes your code organized and easy to load.
0
0
PSR-4 directory mapping in PHP
Introduction
When you want to organize your PHP classes in folders that match their namespaces.
When you use Composer to autoload your PHP classes without manually including files.
When you build a PHP project with many classes and want to keep code clean and easy to maintain.
Syntax
PHP
"psr-4": { "Namespace\\": "path/to/folder/" }
The left side is the namespace prefix with double backslashes escaped.
The right side is the folder path where classes for that namespace live.
Examples
This maps the namespace
App\ to the src/ folder.PHP
"psr-4": { "App\\": "src/" }
This maps the namespace
MyProject\Utils\ to the lib/utils/ folder.PHP
"psr-4": { "MyProject\\Utils\\": "lib/utils/" }
Sample Program
This example shows a class Hello inside the App namespace mapped to the src/ folder. Composer autoloads the class automatically.
PHP
<?php // File: src/Hello.php namespace App; class Hello { public function say() { return "Hello from App\\Hello!"; } } // File: test.php require 'vendor/autoload.php'; use App\Hello; $greet = new Hello(); echo $greet->say();
OutputSuccess
Important Notes
Make sure the folder path ends with a slash /.
Namespace and folder structure must match exactly for autoloading to work.
Composer's autoload section in composer.json is where you set PSR-4 mapping.
Summary
PSR-4 maps namespaces to folders for automatic class loading.
It keeps your PHP code organized and easy to maintain.
Use Composer to set up and use PSR-4 autoloading in your projects.