A modern approach to environment variables using JSON instead of .env
files, with built-in validation via JSON Schema.
composer require koriym/env-json
// Load and validate environment variables
$env = (new EnvJson())->load(__DIR__);
// Access variables
echo $env->DATABASE_URL;
echo getenv('DATABASE_URL');
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["DATABASE_URL", "API_KEY"],
"properties": {
"DATABASE_URL": {
"description": "Database connection string",
"pattern": "^mysql://.*"
},
"API_KEY": {
"description": "API authentication key",
"minLength": 32
},
"DEBUG_MODE": {
"description": "Enable debug output",
"enum": ["true", "false"],
"default": "false"
}
}
}
{
"$schema": "./env.schema.json",
"DATABASE_URL": "mysql://user:pass@localhost/mydb",
"API_KEY": "1234567890abcdef1234567890abcdef",
"DEBUG_MODE": "true"
}
Do not use "type": "boolean"
or "type": "integer"
in your schema. Use "enum": ["true", "false"]
for booleans and "pattern": "^[0-9]+$"
for numbers.
bin/ini2json .env
This generates both env.schema.json
and env.json
files.
# Load variables into current shell
source <(bin/envjson)
# Specify custom directory
source <(bin/envjson -d ./config)
# Output formats
bin/envjson --output=shell # export FOO="bar"
bin/envjson --output=fpm # env[FOO] = "bar"
bin/envjson --output=ini # FOO="bar"
# Run all demos
php demo/run.php
# Or run individual demos
php demo/env-json-1/run.php # Basic usage
php demo/convert/run.php # Convert .env to JSON
php demo/error-handling/run.php # Error handling examples
php demo/validation/run.php # Schema validation examples
php demo/envjson-cli/run.php # CLI tool usage examples
Configuration deserves more than plaintext. Structure it. Validate it. Understand it—with env.json!