Lesson 8 / 10

Namespaces, Composer and Autoloading

As a project grows past a handful of files, two problems reliably show up: class names collide with each other, and you end up hand-writing dozens of require statements just to make everything available. Namespaces and Composer solve both problems together.

Namespaces

namespace TutolineCourses;nnclass Course {n    // ...n}nn// elsewhere:nuse TutolineCoursesCourse;n$course = new Course();

A namespace is conceptually like a folder for class names — two different libraries can both define a class called Course without conflicting, as long as they live in different namespaces. Namespaces typically follow a project’s folder structure, which is also what makes Composer’s autoloading (below) work automatically.

Composer and autoloading

composer initncomposer require monolog/monolog

Composer is PHP’s standard package manager — it downloads libraries into a vendor/ folder and generates an autoloader file, so a single require "vendor/autoload.php"; at the top of your script makes every installed package and your own namespaced classes available, with no manual require statement per file. This is exactly how WordPress plugins built with modern tooling, and virtually every serious PHP framework, manage their dependencies.

PSR-4 autoloading, briefly

{n    "autoload": {n        "psr-4": {n            "Tutoline\": "src/"n        }n    }n}

This composer.json snippet tells Composer’s autoloader that any class in the Tutoline namespace can be found under the src/ folder, following the namespace as a matching folder path — TutolineCoursesCourse would be expected at src/Courses/Course.php. Following this convention is why autoloading can find your classes automatically without you registering each file by hand.