Intermediate LevelPHP 8+
How does Composer PSR-4 Autoloading work with PHP Namespaces?
❓ Interview Prompt: Explain PSR-4 file path mapping rules, namespaces, and how vendor/autoload.php loads classes dynamically.
PSR-4 is the industry-standard autoloading specification managed by Composer, mapping PHP Namespaces directly to directory structures.
How PSR-4 Works:
In your 'composer.json' file, map a base namespace prefix to a directory:
```json
"autoload": {
"psr-4": { "App\\": "src/" }
}
```
When you instantiate 'new AppControllersUserController()', Composer's autoloader intercepts the request, maps 'App' to 'src/', appends 'Controllers/UserController.php', and executes 'require' lazily on demand!
Code Implementation Example
php
<?php
// Entry Point: public/index.php
declare(strict_types=1);
// Include Composer autoloader EXACTLY ONCE at application boot!
require_once __DIR__ . '/../vendor/autoload.php';
// Instantiate classes directly without ANY manual require_once statements!
$logger = new MonologLogger('app');
$invoiceService = new AppServicesInvoiceService($logger);💡PSR-4 namespace autoloading eliminating manual require_once statements.
🎯 Interview Key Takeaway
Map namespaces to directories in composer.json under psr-4. Require vendor/autoload.php once to load classes lazily.
#Composer#PSR-4#Autoloading#Intermediate
Back to all PHP 8+ Questions→