PHP Namespaces & Autoloading

Namespaces stop class names from colliding — your Order and a library's Order can coexist.

PHP
<?php
namespace App\Models;

class Order { }

The namespace declaration must be the first statement in the file.

Using a namespaced class

PHP
<?php
namespace App\Controllers;

use App\Models\Order;
use App\Services\Payment as PaymentService;

$order = new Order();
$pay   = new PaymentService();

Without the use line you'd write the fully-qualified name every time: new \App\Models\Order().

The leading backslash

Inside a namespace, built-in classes need a leading \ or PHP looks for them in the current namespace:

PHP
<?php
namespace App;

$d = new \DateTime();      // correct
// $d = new DateTime();    // looks for App\DateTime — error

PSR-4 autoloading

Rather than require-ing every class file, map namespaces to directories once. In composer.json:

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

Then App\Models\Order is loaded automatically from src/Models/Order.php. Run composer dump-autoload after changing this, and include the autoloader once at the entry point:

PHP
<?php
require __DIR__ . '/vendor/autoload.php';

use App\Models\Order;

$order = new Order();

Convention

  • One class per file.
  • File name matches the class name exactly, including case.
  • Directory structure mirrors the namespace.

Follow those three rules and autoloading simply works — this is how essentially every modern PHP project (Laravel, Symfony, WordPress plugins with Composer) is organised.