mykehowells/dotenv
Load and manage environment variables in PHP/Laravel using .env files. Simple API for reading config values across local, staging, and production setups, making it easy to keep secrets and per-environment settings out of code.
Installation:
composer require mykehowells/dotenv
Add to composer.json under autoload:
{
"autoload": {
"files": [
"vendor/mykemeynell/dotenv/dotenv.php"
]
}
}
Run composer dump-autoload.
Basic Usage:
Place a .env file in your project root (e.g., APP_NAME=MyApp).
Load it in your bootstrap file (e.g., public/index.php or bootstrap/app.php):
require __DIR__.'/vendor/mykemeynell/dotenv/dotenv.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
First Use Case: Access environment variables like Laravel:
$appName = env('APP_NAME', 'DefaultApp'); // Returns 'MyApp' or fallback
Standard Laravel Integration:
Replace env() calls in non-Laravel projects with this package’s env() function. Mimics Laravel’s behavior:
$dbHost = env('DB_HOST', 'localhost');
Configuration Files:
Use .env for environment-specific settings (e.g., DB_PASSWORD=secret123 in .env.dev).
Override defaults dynamically:
if (app()->environment('local')) {
$dotenv->load(__DIR__.'/../.env.local');
}
Validation:
Validate .env values early (e.g., in a bootstrap/validate-env.php):
$requiredVars = ['APP_KEY', 'DB_HOST'];
foreach ($requiredVars as $var) {
if (empty(env($var))) {
throw new RuntimeException("Missing required env var: {$var}");
}
}
Testing:
Load test-specific .env files:
$dotenv->load(__DIR__.'/../../.env.testing');
boot() method for global access..env values in production to avoid repeated file reads:
if (!app()->bound('env-cache')) {
app()->singleton('env-cache', function () {
return $dotenv->parse();
});
}
$value = env('APP_DEBUG', env('DEBUG_MODE', false));
File Paths:
.env in the root directory by default. Explicitly specify paths:
$dotenv = new Dotenv\Dotenv(__DIR__.'/../config');
Caching Issues:
.env won’t reflect until the script restarts. Clear opcache or restart PHP-FPM:
php -r "opcache_reset();"
Variable Overrides:
load() calls overwrite previous values. Use separate files for environments:
$dotenv->load(__DIR__.'/../.env.base');
$dotenv->load(__DIR__.'/../.env.local'); // Overrides base
Security:
.env to version control (add to .gitignore).php artisan env:encrypt (if paired with Laravel) or manually encrypt sensitive values..env keys or file paths. Use:
var_dump(env()); // List all loaded variables
.env files must use KEY=VALUE format. Validate with:
php -r "if (!file_exists('.env')) die('Missing .env file\n');"
Custom Parsers:
Extend Dotenv\Dotenv to support non-standard formats (e.g., YAML):
class CustomDotenv extends Dotenv\Dotenv {
public function parse() {
$data = yaml_parse_file($this->filePath);
return array_merge(parent::parse(), $data);
}
}
Event Hooks:
Trigger events on .env load (e.g., log changes):
$dotenv->onLoad(function () {
logger()->info('Environment loaded:', ['vars' => env()]);
});
Dynamic Paths:
Use runtime logic to determine .env paths:
$envPath = getenv('ENV_PATH') ?: __DIR__.'/../.env';
$dotenv->load($envPath);
How can I help you explore Laravel packages today?