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

Loads environment variables from a .env file.

Parameters:

  • $path (string) - Path to the .env file

Example:

use Stilmark\Base\Env;

Env::load(__DIR__ . '/.env');
Env::load('/path/to/custom.env');

get(string $key, mixed $default = null): mixed

Retrieves 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

Sets an environment variable at runtime.

Parameters:

  • $key (string) - Environment variable name

  • $value (mixed) - Value to set

Example:

has(string $key): bool

Checks if an environment variable exists.

Parameters:

  • $key (string) - Environment variable name

Returns: true if variable exists, false otherwise

Example:

all(): array

Returns all environment variables as an associative array.

Returns: Array of all environment variables

Example:

clear(): void

Clears 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

  1. Use descriptive variable names: GOOGLE_CLIENT_ID instead of GCI

  2. Group related variables: Use prefixes like DB_, REDIS_, MAIL_

  3. Provide sensible defaults: Always specify defaults for non-critical settings

  4. Validate early: Check required variables during application bootstrap

  5. Document variables: Maintain an .env.example file with all variables

  6. Environment-specific files: Use .env.local, .env.production for overrides

Last updated