PHP 8: Modern PHP Development · Composer, Autoloading and PSR Standards
Namespaces and PSR-4 Autoloading
Organize code with namespaces and let Composer load classes automatically.
Namespaces prevent naming collisions and group related code (App\Billing\Invoice). PSR-4 maps a namespace prefix to a directory: with "App\\": "src/", the class App\Billing\Invoice lives in src/Billing/Invoice.php. Composer generates an autoloader, so you only require 'vendor/autoload.php' once in your entry point. Use use statements to import classes, functions and constants.
<?php
// src/Billing/InvoiceService.php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exception\InvoiceNotFound;
use Psr\Log\LoggerInterface;
final class InvoiceService
{
public function __construct(private InvoiceRepository $invoices, private LoggerInterface $logger) {}
}
// public/index.php
require __DIR__ . '/../vendor/autoload.php';
$service = $container->get(App\Billing\InvoiceService::class);
Common pitfalls
- File path casing not matching the class name — works on macOS, fails on Linux.
- Forgetting
composer dump-autoloadafter changing autoload config. - Putting multiple classes in one file under PSR-4.
Key points
- One class per file, path mirrors namespace
- Require Composer's autoloader once
- Use optimized/authoritative class maps in production
Further reading: PSR-4: Autoloader
Practice questions
With PSR-4 mapping App\\ => src/, where is App\Http\Controllers\HomeController?
Answer
In src/Http/Controllers/HomeController.php. The prefix is stripped and remaining namespace segments become directories.
Why might autoloading work locally but fail in a Linux container?
Answer
Linux file systems are case-sensitive. A file named Homecontroller.php matches HomeController on macOS/Windows but not on Linux.
Open in the app to mark lessons complete, take notes and track your progress.