php-standard-library/env
Tiny PHP utility for reading environment variables with sensible defaults and type casting. Helps centralize access to config via env(), supports required keys, fallback values, and safe handling when variables are missing or empty.
Installation:
composer require php-standard-library/env
Add to composer.json under autoload if not auto-discovered:
"autoload": {
"psr-4": {
"App\\": "app/",
"PhpStandardLibrary\\Env\\": "vendor/php-standard-library/env/src/"
}
}
Run composer dump-autoload.
First Use Case: Fetch a string env var with a fallback:
use PhpStandardLibrary\Env\Env;
$appName = Env::get('APP_NAME', 'MyApp');
Where to Look First:
Env class methods: get(), getBool(), getInt(), getArray(), etc.tests/ for usage examples (if included).Centralized Configuration Access:
Replace scattered getenv() calls with a single entry point:
// Before
$debug = getenv('APP_DEBUG') === 'true';
// After
$debug = Env::getBool('APP_DEBUG', false);
Type-Safe Retrieval: Use typed methods to avoid manual casting:
$port = Env::getInt('APP_PORT', 8000);
$enabled = Env::getBool('FEATURE_X', true);
$tags = Env::getArray('ALLOWED_TAGS', []);
Framework Integration:
config('app.name') with Env::get('APP_NAME') for runtime overrides.ParameterBag or Dotenv alternatives for dynamic configs.index.php:
require __DIR__.'/vendor/autoload.php';
$env = new PhpStandardLibrary\Env\Env();
Validation Layer: Combine with validation libraries (e.g., Respect/Validation) for runtime checks:
$timeout = Env::getInt('HTTP_TIMEOUT');
$validator = new Validator();
$validator->validate($timeout, Validation::numeric()->positive());
Environment-Specific Bootstrapping: Load different configs per environment:
$env = Env::get('APP_ENV', 'local');
$config = require __DIR__."/config/{$env}.php";
vlucas/phpdotenv for .env files:
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$value = Env::get('DB_HOST');
Env in unit tests:
$env = $this->getMockBuilder(PhpStandardLibrary\Env\Env::class)
->disableOriginalConstructor()
->onlyMethods(['get'])
->getMock();
$env->method('get')->with('API_KEY')->willReturn('test_key');
Case Sensitivity:
Env vars are case-sensitive by default (e.g., APP_DEBUG ≠ app_debug). Use Env::get('APP_DEBUG', false) consistently.
Empty Values:
Env::get() returns null for missing/empty vars. Always provide defaults:
// Bad: Assumes 'APP_NAME' exists
$name = Env::get('APP_NAME');
// Good: Explicit fallback
$name = Env::get('APP_NAME', 'default');
Type Coercion Quirks:
getBool() treats "1", "true", "on" as true; "0", "false", "off" as false. Empty strings return false.getInt() returns 0 for empty strings (not null). Use Env::get('VAR') === null to check for missing vars.Overriding Defaults:
Avoid hardcoding defaults in Env::get() calls. Centralize them in a config file or service:
// config/env.php
return [
'APP_NAME' => 'MyApp',
'DEBUG' => false,
];
Performance:
The package is lightweight, but avoid calling Env::get() in tight loops. Cache results if needed.
Env::has('VAR') to check existence before retrieval:
if (Env::has('DB_PASSWORD')) {
$password = Env::get('DB_PASSWORD');
}
$raw = getenv('VAR');
error_log("Raw value for VAR: " . json_encode($raw));
# GitHub Actions example
env:
APP_ENV: production
DB_HOST: ${{ secrets.DB_HOST }}
Custom Types:
Extend the Env class to add methods for complex types (e.g., getJson()):
class ExtendedEnv extends PhpStandardLibrary\Env\Env {
public static function getJson(string $key, mixed $default = null): mixed {
$value = self::get($key, $default);
return json_decode($value, true);
}
}
Custom Sources: Override the data source (e.g., read from a database or API):
class CustomEnv extends PhpStandardLibrary\Env\Env {
protected static function getSource(): array {
return $this->fetchFromDatabase();
}
}
Validation Hooks: Add pre-get validation:
Env::extend('validated', function ($key, $default = null) {
$value = Env::get($key, $default);
if ($key === 'API_KEY' && empty($value)) {
throw new RuntimeException('API_KEY is required');
}
return $value;
});
Framework-Specific Adapters: Create adapters for Laravel/Symfony to integrate with their config systems:
class LaravelEnvAdapter {
public static function get(string $key, mixed $default = null) {
return config($key, Env::get($key, $default));
}
}
.env:
putenv('APP_ENV=testing');
$this->assertEquals('testing', Env::get('APP_ENV'));
getenv(), $_ENV, and $_SERVER. Use ini_set('variables_order', 'EGPCS') to control this if needed.$key = strtoupper('app_name');
How can I help you explore Laravel packages today?