Lab 02: Namespaces & PSR-4 Autoloading

Objective

Master PHP namespaces for collision-free code organisation, PSR-4 autoloading conventions, Composer's autoload configuration, use aliases, and namespace-based class discovery. Build a multi-namespace product catalogue that mirrors real-world package structure.

Background

Before namespaces (PHP 5.3+), class names like Product would collide across libraries. Namespaces solve this by prefixing class names with a path: Inno\Catalogue\Product is distinct from Vendor\Ecom\Product. PSR-4 maps namespace prefixes to filesystem paths — Inno\Catalogue\Product maps to src/Catalogue/Product.php. Composer reads composer.json to generate an autoloader that loads classes on demand without manual require calls.

Time

25 minutes

Prerequisites

  • PHP Foundations Lab 13 (Namespaces & Autoloading)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Basic namespaces and use aliases

Every PHP file should declare its namespace as the very first statement (after <?php). When referencing a class from another namespace, you either use the fully-qualified name (\Inno\Catalogue\Product) or import it with use. The as keyword creates an alias for readability.

💡 Namespaces are case-insensitive in PHP, but PSR-4 requires case-sensitivity on case-sensitive filesystems (Linux). Always match the namespace declaration exactly to the directory structure. Inno\Catalogue\Product must live at src/Catalogue/Product.php — wrong case on Linux will cause "class not found" errors in production even if it works on macOS (case-insensitive HFS+).

📸 Verified Output:


Step 2: PSR-4 directory simulation + class discovery

📸 Verified Output:


Step 3: use grouping, constants & functions in namespaces

PHP 7+ allows grouping use imports with braces. Namespaces can also contain constants and functions (not just classes).

📸 Verified Output:


Summary

Concept
Syntax
Purpose

Declare namespace

namespace Inno\Catalogue;

Scope the file's symbols

Import class

use Inno\Catalogue\Product;

Short name in current file

Alias

use Inno\Catalogue\Product as P;

Rename to avoid collision

FQN

new \Inno\Catalogue\Product()

Always works, no import needed

Namespace constant

use const Inno\Config\VERSION;

Import namespaced constant

PSR-4 autoloader

spl_autoload_register(...)

Auto-load classes from files

Further Reading

Last updated