PHPackages                             monkeyscloud/monkeyslegion-env - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. monkeyscloud/monkeyslegion-env

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

monkeyscloud/monkeyslegion-env
==============================

Environment variable management library for PHP applications

1.0.1(2mo ago)0541↑116.1%1MITPHPPHP ^8.4

Since Apr 3Pushed 2mo agoCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Env)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-env)[ RSS](/packages/monkeyscloud-monkeyslegion-env/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (6)Versions (3)Used By (1)

MonkeysLegion-Env
=================

[](#monkeyslegion-env)

A modern, type-safe environment variable management library for PHP 8.4+.

Features
--------

[](#features)

- 🔒 **Type-safe** - Full type hints with strict types enabled
- 🎯 **Simple API** - Clean, intuitive interface for environment management
- 📁 **Multiple .env files** - Support for environment-specific configurations
- 🔄 **Typed getters** - Built-in methods for boolean, integer, and float conversions
- 🛡️ **Error handling** - Custom exceptions for better debugging
- ✨ **Zero config** - Works out of the box with sensible defaults

Installation
------------

[](#installation)

```
composer require monkeyscloud/monkeyslegion-env
```

Quick Start
-----------

[](#quick-start)

```
use MonkeysLegion\Env\EnvManager;
use MonkeysLegion\Env\Loaders\DotenvLoader;
use MonkeysLegion\Env\Repositories\NativeEnvRepository;

// Initialize the manager
$manager = new EnvManager(
    new DotenvLoader(),
    new NativeEnvRepository()
);

// Load environment variables from .env files
$manager->boot(__DIR__);

// Now you can use the manager directly with proxy methods!
$appName = $manager->get('APP_NAME', 'MyApp');
$debug = $manager->getBool('DEBUG', false);
$port = $manager->getInt('PORT', 8080);
$timeout = $manager->getFloat('TIMEOUT', 30.0);

// You can also explicitly return null as default
$apiKey = $manager->get('API_KEY', null);
if ($apiKey === null) {
    // Handle missing API key
}

// Check if a variable exists
if ($manager->has('DATABASE_URL')) {
    $dbUrl = $manager->get('DATABASE_URL');
}

// Remove a variable
$manager->unset('TEMP_VALUE');

// Or access the repository if you prefer
$repo = $manager->getRepository();
$dbUrl = $repo->get('DATABASE_URL');
```

Environment File Loading
------------------------

[](#environment-file-loading)

The library loads `.env` files in the following priority order (highest to lowest):

1. `.env.{APP_ENV}.local` (e.g., `.env.production.local`)
2. `.env.{APP_ENV}` (e.g., `.env.production`)
3. `.env.local`
4. `.env`

The `APP_ENV` variable can be set as a system environment variable to determine which files to load. If not set, it defaults to `dev`.

### Example .env File

[](#example-env-file)

```
APP_NAME=MyApplication
APP_ENV=production
DEBUG=false
PORT=8080
DATABASE_URL=mysql://user:pass@localhost/db
TIMEOUT=30.5
```

API Reference
-------------

[](#api-reference)

### EnvManager

[](#envmanager)

The main orchestrator for loading and managing environment variables. Provides convenient proxy methods for direct access.

#### Methods

[](#methods)

**Bootstrap:**

- `boot(string $path): void` - Load environment variables from the specified path
- `isBooted(): bool` - Check if environment has been bootstrapped

**Repository Access:**

- `getRepository(): EnvRepositoryInterface` - Get the repository instance

**Proxy Methods (Convenient Direct Access):**

- `get(string $key, ?string $default = ''): ?string` - Get a variable as a string (nullable)
- `getBool(string $key, bool $default = false): bool` - Get as boolean
- `getInt(string $key, int $default = 0): int` - Get as integer
- `getFloat(string $key, float $default = 0.0): float` - Get as float
- `set(string $key, string $value): void` - Set a single variable
- `setMany(array $variables): void` - Set multiple variables
- `has(string $key): bool` - Check if a variable exists
- `unset(string $key): void` - Remove a variable

**Usage:**

```
$manager->boot(__DIR__);

// Use proxy methods for convenience
$debug = $manager->getBool('DEBUG');
$port = $manager->getInt('PORT', 3000);

// Or access repository directly if needed
$repo = $manager->getRepository();
```

### NativeEnvRepository

[](#nativeenvrepository)

Manages environment variables using PHP's native `$_ENV`, `$_SERVER`, and `getenv()`.

#### NativeEnvRepository Methods

[](#nativeenvrepository-methods)

**String Access:**

- `get(string $key, ?string $default = ''): ?string` - Get a variable as a string
    - Returns the environment variable value or the default
    - Can return `null` if explicitly set as default: `get('KEY', null)`
    - Empty string default if not provided: `get('KEY')`

**Typed Access:**

- `getBool(string $key, bool $default = false): bool` - Get as boolean
    - Recognizes: `true`, `false`, `1`, `0`, `yes`, `no`, `on`, `off`
- `getInt(string $key, int $default = 0): int` - Get as integer
- `getFloat(string $key, float $default = 0.0): float` - Get as float

**Modification:**

- `set(string $key, string $value): void` - Set a single variable
- `setMany(array $variables): void` - Set multiple variables at once
- `unset(string $key): void` - Remove a variable from all environment sources

**Checking:**

- `has(string $key): bool` - Check if a variable exists

### DotenvLoader

[](#dotenvloader)

Loads environment variables from `.env` files using [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv).

#### DotenvLoader Methods

[](#dotenvloader-methods)

- `load(string $path): array` - Load environment files from the specified directory

Error Handling
--------------

[](#error-handling)

The library provides custom exceptions for better error handling:

### EnvLoadingException

[](#envloadingexception)

Thrown when environment files cannot be loaded.

```
use MonkeysLegion\Env\Exceptions\EnvLoadingException;

try {
    $manager->boot('/invalid/path');
} catch (EnvLoadingException $e) {
    // Handle loading errors
    echo "Failed to load environment: " . $e->getMessage();
}
```

### InvalidEnvironmentVariableException

[](#invalidenvironmentvariableexception)

Thrown when setting invalid environment variable types.

```
use MonkeysLegion\Env\Exceptions\InvalidEnvironmentVariableException;

try {
    $repo->setMany(['KEY' => ['invalid' => 'array']]);
} catch (InvalidEnvironmentVariableException $e) {
    // Handle validation errors
    echo "Invalid variable: " . $e->getMessage();
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Protecting System Variables

[](#protecting-system-variables)

The library automatically protects system-level environment variables. If `APP_ENV` is set as a system variable, it won't be overwritten by `.env` files:

```
# System level
export APP_ENV=production

# Even if .env contains APP_ENV=dev, the system value (production) takes precedence
```

### Custom Implementations

[](#custom-implementations)

You can create custom loaders and repositories by implementing the provided interfaces:

```
use MonkeysLegion\Env\Contracts\EnvLoaderInterface;
use MonkeysLegion\Env\Contracts\EnvRepositoryInterface;

class CustomLoader implements EnvLoaderInterface {
    public function load(string $path): array {
        // Your custom loading logic
    }
}

class CustomRepository implements EnvRepositoryInterface {
    // Implement required methods
}

$manager = new EnvManager(new CustomLoader(), new CustomRepository());
```

Type Conversion Examples
------------------------

[](#type-conversion-examples)

### Boolean Conversion

[](#boolean-conversion)

```
// .env file:
// DEBUG=true
// FEATURE_FLAG=yes
// MAINTENANCE=0

$debug = $repo->getBool('DEBUG');           // true
$feature = $repo->getBool('FEATURE_FLAG');  // true
$maintenance = $repo->getBool('MAINTENANCE'); // false
```

### Integer and Float Conversion

[](#integer-and-float-conversion)

```
// .env file:
// PORT=8080
// MAX_CONNECTIONS=100
// TIMEOUT=30.5
// TAX_RATE=0.075

$port = $repo->getInt('PORT');              // 8080
$maxConn = $repo->getInt('MAX_CONNECTIONS'); // 100
$timeout = $repo->getFloat('TIMEOUT');      // 30.5
$taxRate = $repo->getFloat('TAX_RATE');     // 0.075
```

Requirements
------------

[](#requirements)

- PHP 8.4 or higher
- Composer

Dependencies
------------

[](#dependencies)

- [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) ^5.6

Development
-----------

[](#development)

### Running Tests

[](#running-tests)

```
composer test
```

### Code Analysis

[](#code-analysis)

```
composer analyze
```

### Test Coverage

[](#test-coverage)

```
composer test:coverage
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Author
------

[](#author)

MonkeysCloud

Support
-------

[](#support)

For issues, questions, or contributions, please use the GitHub issue tracker.

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance85

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~15 days

Total

2

Last Release

76d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2913369?v=4)[Jorge Peraza](/maintainers/yorchperaza)[@yorchperaza](https://github.com/yorchperaza)

---

Top Contributors

[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (6 commits)")[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-env/health.svg)

```
[![Health](https://phpackages.com/badges/monkeyscloud-monkeyslegion-env/health.svg)](https://phpackages.com/packages/monkeyscloud-monkeyslegion-env)
```

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[vinkla/wordplate

The WordPlate boilerplate

2.2k5.3k](/packages/vinkla-wordplate)[lullabot/drainpipe

An automated build tool to allow projects to have a set standardized operations scripts.

43785.5k4](/packages/lullabot-drainpipe)[phlak/directory-lister

PHP directory lister

2.5k1.4k](/packages/phlak-directory-lister)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
