The Analogy: Commissioning a Machine on Site
A machine tool built and proven on the factory's test rig is not simply switched on when it reaches a customer's plant. It must be commissioned. The machine is identical, but the plant's mains voltage, the local material feed rates, and the address the machine uses on the site network all differ from the rig it was tested on. None of these values are welded into the machine. They live on a settings card that the commissioning engineer loads on arrival, so one identical machine serves every site by reading a different card.
The most sensitive settings never travel with the machine at all. The master unlock code, and the supplier account number the machine dials to reorder consumables, are handed to the site manager in a sealed envelope and entered on site. They are never printed in the manual that ships in the crate with every unit. Print them in the manual and every customer, and everyone who ever glances at a manual, holds the keys. Keep them off the machine and out of the manual, and a leaked manual reveals nothing dangerous.
Commissioning follows a checklist before the machine is handed over. Guards that were left open on the test rig for probing are closed. The verbose diagnostic readout that scrolled every internal value for the engineers is switched to the terse operator display. The machine is set to its efficient production mode rather than the slow, instrumented rig mode. Only when every item on the list is signed off does the machine go live.
The dangerous failure is leaving a workshop setting enabled in production. If the verbose diagnostic mode -- which prints every internal value, including the contents of that sealed envelope, onto a display anyone on the floor can read -- is left on because nobody worked the checklist, the machine runs perfectly while broadcasting its own secrets. It is not a crash. It is a silent leak that looks exactly like normal operation, and it is discovered only when someone who should never have had the unlock code turns out to have it all along.
Syntax or Core Structure
The central rule of deployment is that configuration comes from the environment, not from the code. One build of your application runs unchanged in every environment; it reads different environment variables in each. In PHP, getenv reads a variable, and you supply a default for the case where it is not set -- the settings card that may or may not be present.
<?php
declare(strict_types=1);
function config(string $key, string $default): string {
$value = getenv($key);
return $value === false ? $default : $value;
}
putenv('APP_ENV=production');
putenv('DB_HOST=db.internal');
echo 'env: ', config('APP_ENV', 'local'), "\n";
echo 'db: ', config('DB_HOST', '127.0.0.1'), "\n";
echo 'log: ', config('LOG_LEVEL', 'info'), "\n";
Output:
env: production
db: db.internal
log: info
The config helper returns the environment value when it is set and the default otherwise, since getenv returns false for a missing variable. Here putenv stands in for the real deployment setting the variables in the server or container environment; APP_ENV and DB_HOST come from that environment, while LOG_LEVEL was never set and falls back to info. The same code, given a different environment, becomes the local development configuration without a single edit.
Technical Depth: Environment Settings, Precedence, and the Checklist
Development versus production settings
The same code must behave differently in each environment, and the differences are exactly the workshop-versus-live distinctions from the analogy.
| Setting | Development | Production |
|---|---|---|
display_errors | On, to see errors fast | Off, never leak to users |
log_errors | On | On |
opcache.enable | Off or revalidated | On |
APP_DEBUG | true | false |
A single flag usually drives the rest: the environment name. From it you derive a coherent policy rather than setting each option independently.
<?php
declare(strict_types=1);
/** @return array{display_errors: bool, log_errors: bool, opcache: bool} */
function errorPolicy(string $env): array {
$isProd = $env === 'production';
return [
'display_errors' => !$isProd,
'log_errors' => true,
'opcache' => $isProd,
];
}
foreach (['local', 'production'] as $env) {
$p = errorPolicy($env);
echo $env, ': display=', $p['display_errors'] ? 'on' : 'off',
' opcache=', $p['opcache'] ? 'on' : 'off', "\n";
}
Output:
local: display=on opcache=off
production: display=off opcache=on
Deriving the whole policy from APP_ENV means the two environments cannot drift apart by someone toggling one option and forgetting another. In production, display_errors is off so a stack trace never reaches a visitor, while opcache is on so PHP does not recompile every file on every request.
Layering configuration and precedence
Locally you keep a .env file for convenience, and it must never be committed. On a server the real environment variables are injected by the platform, and they must win over any file, so a leftover .env cannot override what the platform set. The parser below reads a .env text, then the lookup lets the real environment take precedence.
<?php
declare(strict_types=1);
/** @return array<string, string> */
function parseDotenv(string $text): array {
$out = [];
foreach (explode("\n", $text) as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
[$k, $v] = array_pad(explode('=', $line, 2), 2, '');
$out[trim($k)] = trim($v);
}
return $out;
}
$dotenv = "# app config\nAPP_ENV=local\nDB_HOST=127.0.0.1\nCACHE=file\n";
$parsed = parseDotenv($dotenv);
putenv('DB_HOST=db.internal');
foreach (['APP_ENV', 'DB_HOST', 'CACHE'] as $key) {
$fromEnv = getenv($key);
$value = $fromEnv !== false ? $fromEnv : ($parsed[$key] ?? '');
echo $key, '=', $value, "\n";
}
Output:
APP_ENV=local
DB_HOST=db.internal
CACHE=file
The file supplies APP_ENV and CACHE, but DB_HOST was set in the real environment, so the lookup returns db.internal and ignores the file's 127.0.0.1. This is the correct precedence: the platform's injected value always beats the checked-out file, which is what lets one repository be safe to deploy to many environments.
Validating the whole environment at boot
Failing on the first missing variable makes for a frustrating deploy: you fix one, redeploy, and hit the next. It is far better to check every required key at once and report all that are absent, so a single boot tells you the complete list to fix.
<?php
declare(strict_types=1);
/**
* @param list<string> $required
* @return list<string>
*/
function missingConfig(array $required): array {
$missing = [];
foreach ($required as $key) {
if (getenv($key) === false) {
$missing[] = $key;
}
}
return $missing;
}
putenv('APP_ENV=production');
putenv('APP_KEY=abc');
$required = ['APP_ENV', 'APP_KEY', 'DB_HOST', 'DB_PASSWORD'];
$missing = missingConfig($required);
if ($missing === []) {
echo "config ok\n";
} else {
echo 'missing: ', implode(', ', $missing), "\n";
echo 'count: ', count($missing), "\n";
}
Output:
missing: DB_HOST, DB_PASSWORD
count: 2
Here APP_ENV and APP_KEY are set but DB_HOST and DB_PASSWORD are not, so the function returns both names and the deploy can report the full gap in one message. Run this at the very start of the bootstrap, before any connection is attempted, and a misconfigured environment stops with a complete, actionable list rather than a trickle of one-at-a-time failures.
A deployment checklist
Going live is a sequence, not a single push, and each step maps to a commissioning task.
| Step | Why it matters |
|---|---|
Install with composer install --no-dev | Exclude dev tools and pin the locked versions |
Set display_errors off | Never leak stack traces or secrets to users |
| Enable and warm opcache | Stop recompiling PHP on every request |
| Run database migrations | Keep the schema in step with the new code |
| Warm caches, then switch traffic | Avoid a cold, slow first request |
Real World Example: A Fail-Fast Config Bootstrap
The safest thing a deployment can do is refuse to start when a required secret is missing, rather than boot in a broken or insecure state. The bootstrap below assembles an immutable Config from the environment, derives debug from the environment name, and throws in production if the application key was never set -- a machine that will not run without its sealed envelope.
<?php
declare(strict_types=1);
final class Config {
public function __construct(
public readonly string $env,
public readonly bool $debug,
public readonly string $dbHost,
public readonly string $appKey,
) {}
}
function loadConfig(): Config {
$env = getenv('APP_ENV') ?: 'local';
$isProd = $env === 'production';
$appKey = getenv('APP_KEY') ?: '';
if ($isProd && $appKey === '') {
throw new RuntimeException('APP_KEY must be set in production');
}
return new Config(
env: $env,
debug: !$isProd,
dbHost: getenv('DB_HOST') ?: '127.0.0.1',
appKey: $appKey,
);
}
putenv('APP_ENV=production');
putenv('DB_HOST=db.internal');
echo 'booting production... ';
try {
$c = loadConfig();
echo "started\n";
} catch (RuntimeException $e) {
echo 'refused: ', $e->getMessage(), "\n";
}
putenv('APP_KEY=s3cr3t-key');
$c = loadConfig();
echo 'env=', $c->env, ' debug=', $c->debug ? 'true' : 'false', ' db=', $c->dbHost, "\n";
echo 'key length=', strlen($c->appKey), "\n";
Output:
booting production... refused: APP_KEY must be set in production
env=production debug=false db=db.internal
key length=10
The Config class uses readonly promoted properties, so once built it cannot be mutated -- configuration is decided at boot and then frozen. loadConfig reads the environment name, derives isProd, and reads the key. The crucial line is the guard: in production with no key, it throws before a single request is served. A misconfigured deploy stops immediately and loudly instead of running with an empty signing key.
The first boot attempt sets APP_ENV to production but never sets APP_KEY, so the guard fires and the bootstrap is refused with a clear message. After the key is provided, the second attempt succeeds: the environment is production, debug is correctly false, the database host is the injected value, and the key is present with the expected length. Deriving debug from the environment guarantees it can never be true in production, which is where the workshop diagnostic mode would leak the most.
The design flaw is that the guard validates presence, not strength or secrecy. Because getenv('APP_KEY') ?: '' collapses both an unset variable and an empty string to the same empty result, and the check only asks whether the key is empty, a weak or placeholder value like changeme sails straight through and boots production happily. The bootstrap also holds the secret in an environment variable, where a stray phpinfo() or a var_dump of the environment would print it -- the very verbose-diagnostic leak the analogy warned about. Failing fast on a missing key is necessary but not sufficient; a real system must also validate the key's length and entropy and keep it out of any output, because "present" and "safe" are not the same guarantee.
Common Mistakes
- Committing secrets to the repository. An API key or database password in a tracked file -- or lingering in git history -- is exposed to everyone with repository access, permanently. Keep secrets in the environment and add
.envto.gitignore.
- Leaving
display_errorson in production. A visible stack trace hands an attacker file paths, query fragments, and sometimes secret values. Turndisplay_errorsoff and record failures withlog_errorsinstead.
- Deploying with
composer update.updatere-resolves versions and can ship code you never tested. Deploy withcomposer install --no-devso production runs exactly the versions the lock file records.
- Hardcoding environment-specific values. A literal
db.internalor a production URL baked into the code means the same build cannot run locally. Read every such value from the environment.
- Forgetting to run migrations. New code that expects a column the live database lacks fails at runtime. Make migrations a required, ordered step of the deploy, not an afterthought.
- Not enabling opcache in production. Without it, PHP recompiles every file on every request and wastes significant CPU. Enable opcache and do not disable its cache in a way that revalidates on each hit.
- Booting despite missing configuration. Silently falling back to a default for a required secret hides a misconfiguration until it causes a subtle failure or a breach. Fail fast and refuse to start without the required values.
- Reusing one
.envacross environments. Copying the production.envto staging leaks production secrets into a weaker environment. Each environment gets its own configuration, set by its own platform.
- Editing files directly on the production server. A hand-patched live file diverges from the repository and is lost on the next deploy. Change code through the repository and redeploy, never in place.
Best Practices
- Read all configuration from the environment so that one immutable build runs everywhere, changing behaviour only through its variables.
- Keep secrets out of the repository entirely; inject them through the platform's environment and gitignore any local
.envfile.
- Turn
display_errorsoff andlog_errorson in production, so failures are recorded without being shown to users.
- Deploy with
composer install --no-dev --optimize-autoloader, running the exact versions the lock file records.
- Fail fast at boot when a required secret or setting is missing, so a misconfiguration stops the deploy rather than reaching users.
- Enable opcache in production and warm it, so requests are never slowed by recompilation.
- Make database migrations an explicit, ordered deploy step, so the schema and the code advance together.
- Treat the deploy as a repeatable script or pipeline, so every release follows the same checklist rather than someone's memory.
Practice Exercises
- Extend the
confighelper with aconfigBoolthat reads a variable and returns true for"1","true", and"on"(case-insensitive) and false otherwise, then test it against several inputs.
- Strengthen
loadConfigso it also rejects anAPP_KEYshorter than sixteen characters in production, and show that a missing key and a short key are both refused while a long key boots.
- Write a function that takes the array from
errorPolicyand returns the list ofini_setcalls it would make, as strings, so a reviewer can see the exact production settings without applying them.
- Given a
.envfile and a set of real environment variables, write a resolver that reports, for each key, whether its final value came from the environment or the file, proving the precedence rule.