alanvdb / php-server-environment
Server environment class and factory
v1.0
2025-05-12 14:58 UTC
Requires
Requires (Dev)
- phpunit/phpunit: ^11.5
This package is auto-updated.
Last update: 2025-05-12 15:02:23 UTC
README
A robust PHP library for managing environment variables with strict type checking and comprehensive error handling.
Features
- Secure environment variable management
- Strict type enforcement
- Immutable system environment variables
- Easy-to-use interface for retrieving environment variables
- Comprehensive exception handling
Installation
Install via Composer:
composer require alanvdb/server-environment
Usage
Basic Usage
use AlanVdb\Server\PhpServerEnvironment; // Create an environment with optional initial variables $env = new PhpServerEnvironment([ 'APP_DEBUG' => 'true', 'APP_ENV' => 'development' ]); // Retrieve an environment variable $debugMode = $env->get('APP_DEBUG'); // returns 'true' // Check if a variable exists $hasEnv = $env->has('APP_ENV'); // returns true
Error Handling
use AlanVdb\Server\Exception\EnvironmentVariableNotFound; use AlanVdb\Server\Exception\CannotMutateEnvironmentVariable; try { // Attempting to get a non-existent variable will throw an exception $value = $env->get('NON_EXISTENT_VAR'); } catch (EnvironmentVariableNotFound $e) { // Handle missing variable } try { // Attempting to modify a system environment variable will throw an exception $env = new PhpServerEnvironment(['PATH' => '/custom/path']); } catch (CannotMutateEnvironmentVariable $e) { // Handle mutation attempt }
Factory
use AlanVdb\Server\PhpServerEnvironmentFactory; $factory = new PhpServerEnvironmentFactory(); $env = $factory->create([ 'APP_DEBUG' => 'true', 'APP_ENV' => 'development' ]);
Requirements
- PHP 8.2+
- Composer
Key Design Principles
- Immutability of system environment variables
- Type safety
- Clear and descriptive exceptions
- Easy integration with existing PHP projects