PHPackages                             crell/envmapper - 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. crell/envmapper

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

crell/envmapper
===============

A simple, fast mapper from environment variables to classed objects.

1.1.0(6mo ago)8713.7k↓43.9%41LGPL-3.0-or-laterPHPPHP ~8.1CI passing

Since Mar 6Pushed 6mo ago2 watchersCompare

[ Source](https://github.com/Crell/EnvMapper)[ Packagist](https://packagist.org/packages/crell/envmapper)[ Docs](https://github.com/Crell/EnvMapper)[ GitHub Sponsors](https://github.com/Crell)[ RSS](/packages/crell-envmapper/feed)WikiDiscussions master Synced 1mo ago

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

EnvMapper
=========

[](#envmapper)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5e88bff9e3bd73ed981093c1ada9fc1ff97972e5b81b88c1f296bbd9329d2baf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f4372656c6c2f456e764d61707065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Crell/EnvMapper)[![Software License](https://camo.githubusercontent.com/bf1c19b4a07c841715e713542bd6e9c2aaf75ffa2ee2aa3987814d99311f799b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4c47504c76332d677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/c3b5630d027c94f4e211666384b37926e4269e223a30b3eca10fca26f3e61e9f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f4372656c6c2f456e764d61707065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Crell/EnvMapper)

Reading environment variables is a common part of most applications. However, it's often done in an ad-hoc and unsafe way, by calling `getenv()` or reading `$_ENV` from an arbitrary place in code. That means error handling, missing-value handling, default values, etc. are scattered about the code base.

This library changes that. It allows you to map environment variables into arbitrary classed objects extremely fast, which allows using the class definition itself for default handling, type safety, etc. That class can then be registered in your dependency injection container to become automatically available to any service.

Usage
-----

[](#usage)

EnvMapper has almost no configuration. Everything is just the class.

```
// Define the class.
class DbSettings
{
    public function __construct(
        // Loads the DB_USER env var.
        public readonly string $dbUser,
        // Loads the DB_PASS env var.
        public readonly string $dbPass,
        // Loads the DB_HOST env var.
        public readonly string $dbHost,
        // Loads the DB_PORT env var.
        public readonly int $dbPort,
        // Loads the DB_NAME env var.
        public readonly string $dbName,
    ) {}
}

$mapper = new Crell\EnvMapper\EnvMapper();

$db = $mapper->map(DbSettings::class);
```

`$db` is now an instance of `DbSettings` with all five properties populated from the environment, if defined. That object may now be used anywhere, passed into a constructor, or whatever. Because its properties are all `readonly`, you can rest assured that no service using this object will be able to modify it.

You can use any class you'd like, however. All that matters is the defined properties (defined via constructor promotion or not). The properties may be whatever visibility you like, and you may include whatever methods you'd like.

### Name mapping and default values

[](#name-mapping-and-default-values)

EnvMapper will convert the name of the property into `UPPER_CASE` style, which is the style typically used for environment variables. It will then look for an environment variable by that name and assign it to that property. That means you may use `lowerCamel` or `snake_case` for object properties. Both will work fine.

If no environment variable is found, but the property has a default value set in the class definition, that default value will be used. If there is no default value, it will be left uninitialized.

Alternatively, you may set `requireValues: true` in the `map()` call. If `requireValues` is set, then a missing property will instead throw a `MissingEnvValue` exception.

```
class MissingStuff
{
    public function __construct(
        public readonly string $notSet,
    ) {}
}

// This will throw a MissingEnvValue exception unless there is a NOT_SET env var defined.
$mapper->map(MissingStuff::class, requireValues: true);
```

### Type enforcement

[](#type-enforcement)

Environment variables are always strings, but you may know out-of-band that they are supposed to be an `int` or `float`. EnvMapper will automatically cast int-like values (like "5" or "42") to integers, and float-like values (like "3.14") to floats, so that they will safely assign to the typed properties on the object.

If a property is typed `bool`, then the values "1", "true", "yes", and "on" (in any case) will evaluate to `true`. Anything else will evaluate to false.

If a value cannot be assigned (for instance, if the `DB_PORT` environment variable was set to `"any"`), then a `TypeMismatch`exception will be thrown.

### dot-env compatibility

[](#dot-env-compatibility)

EnvMapper reads values from `$_ENV` by default. If you are using a library that reads `.env` files into the environment, it should work fine with EnvMapper provided it populates `$_ENV`. EnvMapper does not use `getenv()` as it is much slower.

Note that your [variables\_order](http://php.net/variables-order) in PHP needs to be set to include `E`, for Environment, in order for `$_ENV` to be populated. If it is not, `$_ENV` will be empty. If you cannot configure your server to populate `$_ENV`, and you cannot switch to a non-broken server, as a fallback you can pass the return of `getenv()` to the `source`parameter, like so:

```
$mapper->map(Environment::class, source: getenv());
```

Common patterns
---------------

[](#common-patterns)

### Registering with a DI Container

[](#registering-with-a-di-container)

The recommended way to use `EnvMapper` is to wire it into your Dependency Injection Container, preferably one that supports auto-wiring. For example, in a Laravel Service Provider you could do this:

```
namespace App\Providers;

use App\Environment;
use Crell\EnvMapper\EnvMapper;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class EnvMapperServiceProvider extends ServiceProvider
{
    // The EnvMapper has no constructor arguments, so registering it is simple.
    public $singletons = [
        EnvMapper::class => EnvMapper::class,
    ];

    public function register(): void
    {
        // When the Environment class is requested, it will be loaded lazily out of the env vars by the mapper.
        // Because it's a singleton, the object will be automatically cached.
        $this->app->singleton(Environment::class, fn(Application $app) => $app[EnvMapper::class]->map(Environment::class));
    }
}
```

In Symfony, you could implement the same configuration in `services.yaml`:

```
services:
    Crell\EnvMapper\EnvMapper: ~

    App\Environment:
      factory:   ['@Crell\EnvMapper\EnvMapper', 'map']
      arguments: ['App\Environment']
```

Now, any service may simply declare a constructor argument of type `Environment` and the container will automatically instantiate and inject the object as needed.

### Testing

[](#testing)

The key reason to use a central environment variable mapper is to make testing easier. Reading the environment directly from each service is a global dependency, which makes testing more difficult. Instead, making a dedicated environment class an injectable service (as in the example above) means any service that uses it may trivially be passed a manually created version.

```
class AService
{
    public function __construct(private readonly AwsSettings $settings) {}

    // ...
}

class AServiceTest extends TestCase
{
    public function testSomething(): void
        $awsSettings = new AwsSettings(awsKey: 'fake', awsSecret: 'fake');

        $s = new Something($awsSettings);

        // ...
    }
}
```

### Multiple environment objects

[](#multiple-environment-objects)

Any environment variables that are set but not present in the specified class will be ignored. That means it's trivially easy to load different variables into different classes. For example:

```
class DbSettings
{
    public function __construct(
        public readonly string $dbUser,
        public readonly string $dbPass,
        public readonly string $dbHost,
        public readonly int $dbPort,
        public readonly string $dbName,
    ) {}
}

class AwsSettings
{
    public function __construct(
        public readonly string $awsKey,
        public readonly string $awsSecret,
    ) {}
}
```

```
// Laravel version.
class EnvMapperServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(DbSettings::class, fn(Application $app) => $app[EnvMapper::class]->map(DbSettings::class));
        $this->app->singleton(AwsSettings::class, fn(Application $app) => $app[EnvMapper::class]->map(AwsSettings::class));
    }
}
```

```
# Symfony version
services:
  Crell\EnvMapper\EnvMapper: ~

  App\DbSettings:
    factory:   ['@Crell\EnvMapper\EnvMapper', 'map']
    arguments: ['App\DbSettings']

  App\AwsSettings:
    factory:   ['@Crell\EnvMapper\EnvMapper', 'map']
    arguments: ['App\AwsSettings']
```

Advanced usage
--------------

[](#advanced-usage)

EnvMapper is designed to be lightweight and fast. For that reason, its feature set is deliberately limited.

However, there are cases you may wish to have a more complex environment setup. For instance, you may want to rename properties more freely, nest related properties inside sub-objects, or map comma-delimited environment variables into an array. EnvMapper is not designed to handle that.

However, its sibling project [`Crell/Serde`](https://www.github.com/Crell/Serde) can do so easily. Serde is a general purpose serialization library, but you can easily feed it `$_ENV` as an array to deserialize from into an object. That gives you access to all of Serde's capability to rename, collect, nest, and otherwise translate data as it's being deserialized into an object. The basic workflow is the same, and registration in your service container is nearly identical.

```
$serde = new SerdeCommon();

$env = $serde->deserialize($_ENV, from: 'array', to: Environment::class);
```

Using Serde will be somewhat slower than using EnvMapper, but both are still very fast and suitable for almost any application.

See the Serde documentation for all of its various options.

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email larry at garfieldtech dot com instead of using the issue tracker.

Credits
-------

[](#credits)

- [Larry Garfield](https://github.com/Crell)
- [All Contributors](../../contributors)

License
-------

[](#license)

The Lesser GPL version 3 or later. Please see [License File](LICENSE.md) for more information.

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance65

Regular maintenance activity

Popularity40

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 86% 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 ~239 days

Total

5

Last Release

209d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/12e28c223b88445f07d697c8805bd856066c947f70b535f6a7e00d2cb311c3c2?d=identicon)[Crell](/maintainers/Crell)

---

Top Contributors

[![Crell](https://avatars.githubusercontent.com/u/254863?v=4)](https://github.com/Crell "Crell (37 commits)")[![Brammm](https://avatars.githubusercontent.com/u/851445?v=4)](https://github.com/Brammm "Brammm (4 commits)")[![bcremer](https://avatars.githubusercontent.com/u/55820?v=4)](https://github.com/bcremer "bcremer (1 commits)")[![sebastianbergmann](https://avatars.githubusercontent.com/u/25218?v=4)](https://github.com/sebastianbergmann "sebastianbergmann (1 commits)")

---

Tags

environmentmap

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/crell-envmapper/health.svg)

```
[![Health](https://phpackages.com/badges/crell-envmapper/health.svg)](https://phpackages.com/packages/crell-envmapper)
```

###  Alternatives

[vlucas/phpdotenv

Loads environment variables from `.env` to `getenv()`, `$\_ENV` and `$\_SERVER` automagically.

13.5k602.4M5.4k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k226.7M2.3k](/packages/symfony-dotenv)[phpcollection/phpcollection

General-Purpose Collection Library for PHP

1.0k64.0M34](/packages/phpcollection-phpcollection)[dasprid/enum

PHP 7.1 enum implementation

379146.0M11](/packages/dasprid-enum)[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49444.8M97](/packages/marc-mabe-php-enum)[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)

PHPackages © 2026

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