Env
Environment variable management with .env file support and runtime configuration.
Overview
The Env class provides a simple interface for managing environment variables in your application. It supports loading from .env files, runtime variable setting, and type-safe value retrieval with defaults.
Class Reference
Static Methods
load(string $path): void
load(string $path): voidLoads environment variables from a .env file.
Parameters:
$path(string) - Path to the.envfile
Example:
use Stilmark\Base\Env;
Env::load(__DIR__ . '/.env');
Env::load('/path/to/custom.env');get(string $key, mixed $default = null): mixed
get(string $key, mixed $default = null): mixedRetrieves an environment variable value.
Parameters:
$key(string) - Environment variable name$default(mixed) - Default value if variable doesn't exist
Returns: The environment variable value or default
Example:
set(string $key, mixed $value): void
set(string $key, mixed $value): voidSets an environment variable at runtime.
Parameters:
$key(string) - Environment variable name$value(mixed) - Value to set
Example:
has(string $key): bool
has(string $key): boolChecks if an environment variable exists.
Parameters:
$key(string) - Environment variable name
Returns: true if variable exists, false otherwise
Example:
all(): array
all(): arrayReturns all environment variables as an associative array.
Returns: Array of all environment variables
Example:
clear(): void
clear(): voidClears all environment variables (useful for testing).
Example:
Usage Patterns
Application Bootstrap
Configuration Classes
Feature Flags
Environment-Specific Logic
.env File Format
Basic Syntax
Advanced Features
Type Conversion
The Env class returns string values by default. Use type casting for other types:
Security Considerations
Sensitive Data
Never commit .env files containing sensitive data to version control:
Environment Validation
Validate required environment variables on application startup:
Testing
Test Environment Setup
Mocking Environment Variables
Best Practices
Use descriptive variable names:
GOOGLE_CLIENT_IDinstead ofGCIGroup related variables: Use prefixes like
DB_,REDIS_,MAIL_Provide sensible defaults: Always specify defaults for non-critical settings
Validate early: Check required variables during application bootstrap
Document variables: Maintain an
.env.examplefile with all variablesEnvironment-specific files: Use
.env.local,.env.productionfor overrides
Last updated