EnvHelper
EnvHelper provides a framework-agnostic way to access environment variables with automatic type casting and framework detection.
Quick Example
Section titled “Quick Example”use Event4u\DataHelpers\Helpers\EnvHelper;
// Get string value$appName = EnvHelper::string('APP_NAME', 'My App');
// Get integer value$port = EnvHelper::int('APP_PORT', 8080);
// Get boolean value$debug = EnvHelper::bool('APP_DEBUG', false);
// Get float value$timeout = EnvHelper::float('TIMEOUT', 30.0);
// Get array value (comma-separated)$allowedHosts = EnvHelper::array('ALLOWED_HOSTS', ['localhost']);Introduction
Section titled “Introduction”EnvHelper provides a unified interface for accessing environment variables across different frameworks.
Key Features
Section titled “Key Features”- Automatic framework detection - No configuration needed
- Type casting - Get values as string, int, float, bool, or array
- Optional Carbon support - Parse dates when Carbon is installed
- Default values - Fallback values when environment variable is not set
- Type-safe - PHPStan Level 9 compliant
Framework Detection
Section titled “Framework Detection”EnvHelper automatically detects your framework:
- Laravel - Uses Laravel’s
env()helper - Symfony - Uses
$_ENVsuperglobal - Plain PHP - Uses
getenv()or$_ENV
Basic Usage
Section titled “Basic Usage”Get Raw Value
Section titled “Get Raw Value”use Event4u\DataHelpers\Helpers\EnvHelper;
// Get raw value$value = EnvHelper::get('DATABASE_URL');
// With default$value = EnvHelper::get('DATABASE_URL', 'mysql://localhost');Get Typed Values
Section titled “Get Typed Values”// String$appName = EnvHelper::string('APP_NAME', 'Default App');
// Integer$port = EnvHelper::int('PORT', 3000);
// Float$timeout = EnvHelper::float('TIMEOUT', 30.5);
// Boolean$debug = EnvHelper::bool('DEBUG', false);
// Array (comma-separated)$hosts = EnvHelper::array('ALLOWED_HOSTS', []);API Reference
Section titled “API Reference”get(string $key, mixed $default = null): mixed
Section titled “get(string $key, mixed $default = null): mixed”Get raw environment variable value.
$value = EnvHelper::get('DATABASE_URL');$value = EnvHelper::get('DATABASE_URL', 'mysql://localhost');string(string $key, ?string $default = null): ?string
Section titled “string(string $key, ?string $default = null): ?string”Get value as string.
$appName = EnvHelper::string('APP_NAME', 'Default App');$env = EnvHelper::string('APP_ENV', 'production');int(string $key, ?int $default = null): ?int
Section titled “int(string $key, ?int $default = null): ?int”Get value as integer.
$port = EnvHelper::int('PORT', 3000);$maxConnections = EnvHelper::int('MAX_CONNECTIONS', 100);float(string $key, ?float $default = null): ?float
Section titled “float(string $key, ?float $default = null): ?float”Get value as float.
$timeout = EnvHelper::float('TIMEOUT', 30.5);$ratio = EnvHelper::float('SAMPLING_RATIO', 0.1);bool(string $key, ?bool $default = null): ?bool
Section titled “bool(string $key, ?bool $default = null): ?bool”Get value as boolean. Recognizes: true, false, 1, 0, yes, no, on, off.
$debug = EnvHelper::bool('DEBUG', false);$enabled = EnvHelper::bool('FEATURE_ENABLED', true);array(string $key, ?array $default = null): ?array
Section titled “array(string $key, ?array $default = null): ?array”Get value as array (comma-separated).
// .env: ALLOWED_HOSTS=localhost,example.com,test.com$hosts = EnvHelper::array('ALLOWED_HOSTS', []);// ['localhost', 'example.com', 'test.com']carbon(string $key, mixed $default = null): Carbon (Optional)
Section titled “carbon(string $key, mixed $default = null): Carbon (Optional)”Get value as Carbon instance. Requires nesbot/carbon package.
// .env: DEPLOYMENT_DATE=2024-01-15$deploymentDate = EnvHelper::carbon('DEPLOYMENT_DATE');// Carbon instanceType Casting Examples
Section titled “Type Casting Examples”Boolean Values
Section titled “Boolean Values”// .env: DEBUG=trueEnvHelper::bool('DEBUG'); // true
// .env: DEBUG=1EnvHelper::bool('DEBUG'); // true
// .env: DEBUG=yesEnvHelper::bool('DEBUG'); // true
// .env: DEBUG=onEnvHelper::bool('DEBUG'); // true
// .env: DEBUG=falseEnvHelper::bool('DEBUG'); // false
// .env: DEBUG=0EnvHelper::bool('DEBUG'); // false
// .env: DEBUG=noEnvHelper::bool('DEBUG'); // false
// .env: DEBUG=offEnvHelper::bool('DEBUG'); // falseArray Values
Section titled “Array Values”// .env: ALLOWED_IPS=192.168.1.1,192.168.1.2,192.168.1.3$ips = EnvHelper::array('ALLOWED_IPS');// ['192.168.1.1', '192.168.1.2', '192.168.1.3']
// .env: ADMIN_EMAILS=admin@example.com,support@example.com$emails = EnvHelper::array('ADMIN_EMAILS');// ['admin@example.com', 'support@example.com']Numeric Values
Section titled “Numeric Values”// .env: MAX_CONNECTIONS=100$max = EnvHelper::int('MAX_CONNECTIONS'); // 100
// .env: TIMEOUT=30.5$timeout = EnvHelper::float('TIMEOUT'); // 30.5
// .env: PORT=8080$port = EnvHelper::int('PORT'); // 8080Error Handling
Section titled “Error Handling”Missing Variables
Section titled “Missing Variables”All methods return null or the default value if the environment variable is not set:
// Variable not set$value = EnvHelper::string('MISSING_VAR'); // null$value = EnvHelper::string('MISSING_VAR', 'default'); // 'default'
// With default values$port = EnvHelper::int('PORT', 3000); // 3000 if PORT not set$debug = EnvHelper::bool('DEBUG', false); // false if DEBUG not setInvalid Type Conversions
Section titled “Invalid Type Conversions”Invalid type conversions throw InvalidArgumentException:
// .env: PORT=not_a_numbertry { EnvHelper::int('PORT');} catch (InvalidArgumentException $e) { echo $e->getMessage(); // "Invalid integer value for PORT"}
// .env: TIMEOUT=invalidtry { EnvHelper::float('TIMEOUT');} catch (InvalidArgumentException $e) { echo $e->getMessage(); // "Invalid float value for TIMEOUT"}Real-World Examples
Section titled “Real-World Examples”Database Configuration
Section titled “Database Configuration”$dbConfig = [ 'host' => EnvHelper::string('DB_HOST', 'localhost'), 'port' => EnvHelper::int('DB_PORT', 3306), 'database' => EnvHelper::string('DB_DATABASE', 'myapp'), 'username' => EnvHelper::string('DB_USERNAME', 'root'), 'password' => EnvHelper::string('DB_PASSWORD', ''),];Application Configuration
Section titled “Application Configuration”$appConfig = [ 'name' => EnvHelper::string('APP_NAME', 'My Application'), 'env' => EnvHelper::string('APP_ENV', 'production'), 'debug' => EnvHelper::bool('APP_DEBUG', false), 'url' => EnvHelper::string('APP_URL', 'http://localhost'), 'timezone' => EnvHelper::string('APP_TIMEZONE', 'UTC'),];Security Configuration
Section titled “Security Configuration”$securityConfig = [ 'allowed_hosts' => EnvHelper::array('ALLOWED_HOSTS', ['localhost']), 'allowed_ips' => EnvHelper::array('ALLOWED_IPS', []), 'rate_limit' => EnvHelper::int('RATE_LIMIT', 60), 'session_lifetime' => EnvHelper::int('SESSION_LIFETIME', 120), 'csrf_enabled' => EnvHelper::bool('CSRF_ENABLED', true),];API Configuration
Section titled “API Configuration”$apiConfig = [ 'base_url' => EnvHelper::string('API_BASE_URL', 'https://api.example.com'), 'timeout' => EnvHelper::float('API_TIMEOUT', 30.0), 'retry_attempts' => EnvHelper::int('API_RETRY_ATTEMPTS', 3), 'verify_ssl' => EnvHelper::bool('API_VERIFY_SSL', true),];Best Practices
Section titled “Best Practices”Use Type-Specific Methods
Section titled “Use Type-Specific Methods”// ❌ Don't use generic get() for typed values$port = (int)EnvHelper::get('PORT', 3000);
// ✅ Use type-specific methods$port = EnvHelper::int('PORT', 3000);Provide Sensible Defaults
Section titled “Provide Sensible Defaults”// ✅ Always provide defaults for optional settings$timeout = EnvHelper::float('TIMEOUT', 30.0);$debug = EnvHelper::bool('DEBUG', false);$maxConnections = EnvHelper::int('MAX_CONNECTIONS', 100);Use Carbon for Dates
Section titled “Use Carbon for Dates”// ✅ Use carbon() for date values$deploymentDate = EnvHelper::carbon('DEPLOYMENT_DATE');$expiryDate = EnvHelper::carbon('LICENSE_EXPIRY');Group Related Configuration
Section titled “Group Related Configuration”// ✅ Group related configurationclass DatabaseConfig{ public static function get(): array { return [ 'host' => EnvHelper::string('DB_HOST', 'localhost'), 'port' => EnvHelper::int('DB_PORT', 3306), 'database' => EnvHelper::string('DB_DATABASE'), 'username' => EnvHelper::string('DB_USERNAME'), 'password' => EnvHelper::string('DB_PASSWORD'), ]; }}See Also
Section titled “See Also”- ConfigHelper - Configuration helper
- Framework Integration - Framework-specific features
- Core Concepts: Configuration - Package configuration