The Analogy: The Hospital Pharmacy's Formulary and Requisition System
A large hospital pharmacy does not simply keep whatever medicines seem useful. It maintains a formulary: a written list that names every medication the hospital agrees to stock and, for each one, the exact form and strength that is acceptable -- not "a painkiller" but "paracetamol 500mg tablets." The formulary is the pharmacy's standing declaration of what it depends on. Anyone can read it and know precisely what the wards are entitled to draw.
A requisition clerk works from that formulary, placing orders with approved wholesalers. The clerk does one thing that matters enormously: every delivery note is filed, recording the exact batch number and manufacturer of what actually arrived. The formulary might say "paracetamol 500mg," but the delivery notes say "batch 7741 from Meddis Labs, received the third of March." If the same order must be reproduced next month, or filled identically at a sister hospital, the notes make it possible to obtain exactly the same items rather than merely something that fits the description.
Once stock arrives it is shelved by a strict scheme -- therapeutic class, then generic name, then strength. A pharmacist locates any drug from its name alone, walking straight to its predetermined position without needing to know which trolley it came off or who unpacked it. When a genuinely new medication is added to the formulary and delivered, it slots into its place under the same scheme automatically; no one has to redesign the shelving to accommodate it.
The system fails the moment the delivery notes are discarded and only the formulary survives. "Paracetamol 500mg" can be satisfied by three different batches from three manufacturers, and without the notes no one can say which is actually on the shelf today or reproduce it elsewhere. Two hospitals working from an identical formulary but keeping no shared notes drift into subtly different stock, and a difference in a supposedly inert filler can matter to a sensitive patient. The list of what you asked for is not the same as the record of what you received, and confusing the two is how a reproducible supply quietly becomes a guess.
Syntax or Core Structure
Composer is PHP's dependency manager and the source of its autoloader. Two files do the work. composer.json is the formulary: it names each package you depend on and the version range you will accept. composer.lock, generated when you install, is the file of delivery notes: it records the exact version of every package that was actually resolved, so a fresh install reproduces an identical set of packages anywhere. A single require entry and an autoload block are enough to start.
{
"name": "acme/shop",
"require": {
"php": ">=8.1",
"monolog/monolog": "^3.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
The require block lists packages as vendor/name mapped to a version constraint (^3.0 here). The autoload block declares a PSR-4 rule: the namespace prefix App\ maps to the src/ directory. From that one line Composer generates an autoloader that turns any class name under App\ into a file path -- exactly the transformation the pharmacy's shelving scheme performs on a drug name. The core of that transformation is a short function.
<?php
declare(strict_types=1);
function resolvePsr4(string $class, string $prefix, string $baseDir): ?string {
if (!str_starts_with($class, $prefix)) {
return null;
}
$relative = substr($class, strlen($prefix));
return $baseDir . str_replace('\\', '/', $relative) . '.php';
}
$classes = ['App\\Model\\User', 'App\\Service\\Mailer', 'Vendor\\Thing'];
foreach ($classes as $c) {
$path = resolvePsr4($c, 'App\\', 'src/');
echo $c, ' => ', ($path ?? 'not handled'), "\n";
}
Output:
App\Model\User => src/Model/User.php
App\Service\Mailer => src/Service/Mailer.php
Vendor\Thing => not handled
The resolver strips the registered prefix, replaces each namespace separator with a directory separator, and appends .php. So App\Model\User becomes src/Model/User.php, while a class outside the registered prefix returns null and is left for another autoloader to handle. Composer writes an optimised version of this logic into vendor/autoload.php, which you include once at the top of your program; from then on, referencing a class loads its file automatically.
Technical Depth: Version Constraints, the Lock File, and Registration
Version constraints
A constraint tells Composer which released versions of a package are acceptable, following semantic versioning. The two you will use most are the caret and the tilde.
| Constraint | Meaning | Allows |
|---|---|---|
^1.2 | Compatible with 1.2 | >=1.2.0 and <2.0.0 |
~1.2 | Reasonably close | >=1.2.0 and <2.0.0 |
~1.2.3 | Patch-level only | >=1.2.3 and <1.3.0 |
1.2.* | Any patch of 1.2 | >=1.2.0 and <1.3.0 |
>=1.2 | At least this | 1.2.0 and upward |
The caret is the usual default: it permits any release that does not bump the major version, on the promise that minor and patch releases stay backward compatible. The following function reproduces the caret rule for a two-part constraint so you can see exactly which versions pass.
<?php
declare(strict_types=1);
function satisfiesCaret(string $version, int $major, int $minor): bool {
$lower = version_compare($version, "$major.$minor.0", '>=');
$upper = version_compare($version, ($major + 1) . '.0.0', '<');
return $lower && $upper;
}
$candidates = ['1.2.0', '1.5.3', '1.9.9', '2.0.0', '1.1.0'];
foreach ($candidates as $v) {
$ok = satisfiesCaret($v, 1, 2) ? 'allowed' : 'blocked';
echo "$v: $ok\n";
}
Output:
1.2.0: allowed
1.5.3: allowed
1.9.9: allowed
2.0.0: blocked
1.1.0: blocked
version_compare handles the awkward parts of comparing dotted versions correctly, including pre-release suffixes. The constraint ^1.2 admits everything from 1.2.0 up to but not including 2.0.0, so 1.9.9 passes while 2.0.0 and the earlier 1.1.0 are rejected.
The lock file
The distinction between the two Composer files is the reproducibility guarantee, and it maps directly onto the pharmacy.
| File | Analogy | Records | Commit it? |
|---|---|---|---|
composer.json | The formulary | Version ranges you accept | Yes |
composer.lock | The delivery notes | Exact resolved versions | Yes |
Commit both. composer install reads the lock file and installs the exact versions it names, so every machine and every teammate gets an identical set. composer update ignores the lock, re-resolves the ranges in composer.json against the latest matching releases, and rewrites the lock with the new results. Deploying with install rather than update is what keeps production identical to what you tested.
Triggering the autoloader
You never call the autoloader directly. Referencing a class that is not yet defined causes PHP to invoke every function registered with spl_autoload_register, in order, until one loads the class.
<?php
declare(strict_types=1);
spl_autoload_register(function (string $class): void {
echo "autoloader asked for: $class\n";
});
class_exists('App\\Model\\Invoice');
class_exists('App\\Service\\Pdf');
Output:
autoloader asked for: App\Model\Invoice
autoloader asked for: App\Service\Pdf
Here class_exists with its default autoload argument asks PHP to try loading each name, so the registered closure fires once per class and reports the fully-qualified name it was handed. A real autoloader would take that name, resolve it to a path, and require the file; this stub only prints it, which makes the trigger mechanism visible on its own.
Real World Example: A Working PSR-4 Autoloader
A small shop has two classes: App\Money, which wraps an integer number of cents, and App\Catalog\Product, which pairs a name with a Money price. In a real project each lives in its own file under src/, and vendor/autoload.php wires them up. The program below stands in for that: it writes the two source files into a temporary src/ tree, registers exactly the PSR-4 autoloader Composer would generate for the App\ prefix, and then uses the classes without a single require for them.
<?php
declare(strict_types=1);
// Build a small src/ tree for the demo (Composer ships these as real files).
$root = sys_get_temp_dir() . '/shop_' . getmypid();
@mkdir($root . '/src/Catalog', 0777, true);
file_put_contents($root . '/src/Money.php', <<<'CLS'
<?php
namespace App;
final class Money {
public function __construct(public readonly int $cents) {}
public function format(): string {
return '$' . number_format($this->cents / 100, 2);
}
}
CLS);
file_put_contents($root . '/src/Catalog/Product.php', <<<'CLS'
<?php
namespace App\Catalog;
use App\Money;
final class Product {
public function __construct(public string $name, public Money $price) {}
public function line(): string {
return $this->name . ': ' . $this->price->format();
}
}
CLS);
// The PSR-4 autoloader Composer generates for "App\\": "src/".
spl_autoload_register(function (string $class) use ($root): void {
$prefix = 'App\\';
if (!str_starts_with($class, $prefix)) {
return;
}
$relative = substr($class, strlen($prefix));
$file = $root . '/src/' . str_replace('\\', '/', $relative) . '.php';
if (is_file($file)) {
require $file;
}
});
$items = [
new App\Catalog\Product('Keyboard', new App\Money(4999)),
new App\Catalog\Product('Monitor', new App\Money(129900)),
];
foreach ($items as $p) {
echo $p->line(), "\n";
}
echo 'total items: ', count($items), "\n";
Output:
Keyboard: $49.99
Monitor: $1,299.00
total items: 2
The autoloader is the heart of the example. When the program reaches new App\Catalog\Product(...), PHP finds that class undefined and hands the name App\Catalog\Product to the registered closure. The closure confirms the name starts with the App\ prefix, strips it to leave Catalog\Product, converts the namespace separators to slashes, and requires src/Catalog/Product.php. Constructing the Product then references App\Money, which triggers the same closure a second time and loads src/Money.php. Neither file is required by hand.
Once both classes are loaded, the collaboration is ordinary object work: each Product holds a Money, and line asks the money to format itself. Money stores cents as an integer to avoid floating-point drift and only divides by a hundred at display time, where number_format adds the two decimal places and the thousands comma -- so 129900 cents prints as $1,299.00. The final line reports the count of items. The whole program depends on the autoloader having resolved two names to two files correctly.
The design flaw is in the hand-written autoloader, and it is the reason you should not maintain one yourself. When a class file is missing or misnamed, the is_file guard makes the closure return silently, so the failure surfaces later as a bare "class not found" fatal at the point of use, with no hint that the autoload rule simply could not find the file. The closure also understands exactly one prefix and is case-sensitive on the resulting path, so it cannot cope with the several prefixes, classmap entries, and fallback directories a real project accumulates. Composer's generated autoloader handles all of that, keeps an optimised classmap so lookups do not touch the filesystem for known classes, and can be configured to complain on a miss -- which is precisely why the one line "App\\": "src/" is worth more than any autoloader you would write by hand.
Common Mistakes
- Committing
composer.jsonbut notcomposer.lock. Without the lock, teammates and servers re-resolve the ranges and can end up on different versions, so "works on my machine" becomes literal. Commit both files, always.
- Running
composer updateon deploy.updatere-resolves every range against the latest releases and rewrites the lock, so production can receive versions you never tested. Deploy withcomposer install, which honours the lock exactly.
- Editing files under
vendor/. Anything invendor/is overwritten on the next install and should not be committed. Patch a dependency through a fork or a proper patching tool, never by hand-editing the installed copy.
- Mismatching namespace and directory under PSR-4. Given the
App\maps tosrc/rule, the classApp\Model\Usermust live atsrc/Model/User.php. A file in the wrong directory, or a class whose name does not match its file, will not autoload.
- Forgetting to include
vendor/autoload.php. Nothing autoloads until that file is required, usually as the first line of your entry point. Omitting it produces "class not found" errors for classes that plainly exist.
- Using an over-loose constraint like
*or>=1.0. These accept future major versions with breaking changes, so an unrelated update can break your build. Prefer the caret, which caps the major version.
- Not regenerating the autoloader after a classmap or namespace change. PSR-4 additions are picked up automatically in development, but classmap entries and optimised builds need
composer dump-autoload; forgetting it hides the new classes.
- Relying on case-insensitive paths.
App\Model\usermay load on Windows or macOS but fail on a Linux server, because PSR-4 path resolution is case-sensitive. Match the case of the class and the file exactly.
- Leaving application code in the global namespace. A class with no namespace cannot be addressed by a PSR-4 rule and forces you back to manual includes. Give every class a namespace under your registered prefix.
Best Practices
- Commit both
composer.jsonandcomposer.lock, and deploy withcomposer installso every environment runs the exact versions the lock records.
- Use
^constraints by default; they allow safe minor and patch upgrades while blocking breaking major releases.
- Map one namespace prefix to one source directory (
App\tosrc/) and mirror the namespace structure in the folder structure, so any class name predicts its file path.
- Include
vendor/autoload.phpexactly once, as early as possible in each entry point, and let autoloading handle the rest.
- Separate development-only tools such as test frameworks and static analysers into
require-dev, and install without them on production.
- Run
composer install --no-dev --optimize-autoloaderon deploy so the autoloader builds a fast classmap and development dependencies are excluded.
- Review what
composer updatechanges in the lock before committing it, treating a dependency bump as a real change worth reading.
- Prefer well-maintained packages, and run
composer auditto catch known vulnerabilities in your dependency tree.
Practice Exercises
- Write a
composer.jsonfor a packageacme/blogthat requires PHP 8.1 or newer andmonolog/monologat^3.0, and maps the namespaceBlog\tosrc/. State which released Monolog versions the constraint would accept.
- Implement a
resolvePsr4that handles several prefixes at once: given a map of prefix to directory, resolve a class name to a path using the first matching prefix and returnnullif none match. Test it withBlog\PostandAdmin\Panel.
- Extend the caret checker to accept a full constraint string such as
^2.3by parsing the major and minor parts yourself, then report which of2.3.0,2.9.1, and3.0.0it allows.
- Build a two-file mini project --
src/Greeter.phpunder namespaceApp, plus an entry script -- that registers a hand-written PSR-4 autoloader, constructs theGreeter, and prints a greeting, proving no explicitrequireofGreeter.phpis needed.