PHPackages                             jpolvora/dotenvy - 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. jpolvora/dotenvy

ActiveLibrary

jpolvora/dotenvy
================

PHP Environment Variables Manager with dotenv (.env) files and validation by example

v0.0.8(3y ago)0297MITPHPPHP &gt;=8.0.0

Since Jan 9Pushed 3y ago1 watchersCompare

[ Source](https://github.com/jpolvora/dotenvy)[ Packagist](https://packagist.org/packages/jpolvora/dotenvy)[ RSS](/packages/jpolvora-dotenvy/feed)WikiDiscussions master Synced today

READMEChangelog (1)DependenciesVersions (9)Used By (0)

Atualizado em 2022

dotenvy
=======

[](#dotenvy)

PHP Environment Variables Manager with dotenv (.env) files and validation by example

The goal is to provide a simple way to work with environment variables

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

[](#installation)

```
composer require jpolvora/dotenvy
```

WorkFlow
========

[](#workflow)

Create a file named `.env.example` which will be shared through your dev team. This file must be commited to your repo. Place you keys and values of your application variables. The format is `KEY=__validation-string__`

For example:

```
#.env.example
API_KEY = trim|fallback(123)|number
CI_ENV = trim|required|enum(development,production)
```

There are some validators are built-in into library

Current available validators are:

- `required`: value cannot be empty, can be set to any string

```
# .env.example
API_KEY=required
# .env
API_KEY=sdkfjsdlk8349759843udj #pass
API_KEY= #fail
```

- `number`: value cannot be empty and must be convertible to an integer (is\_numeric)

```
# .env.example
PORT=number
# .env
PORT=8080 #pass
PORT=abc #fail
```

- `boolean`: value cannot be empty and must be convertible to boolean (filter\_var)

```
# .env.example
ENABLED=boolean
# .env
ENABLED=1 #pass
ENABLED=true #pass
ENABLED=0 #pass
ENABLED=FALSE #pass
ENABLED=foo #fail
```

- `enum`: value cannot be empty and should be co

```
# .env.example
NODE_ENV=enum(development,production)
# .env
NODE_ENV=development #pass
NODE_ENV=production #pass
NODE_ENV= #FAIL
NODE_ENV=staging #fail
```

- `fallback`:Value can be empty, but will be fallback to desired value

```
# .env.example
APP_LANG=fallback(en-us)
# .env
APP_LANG=pt-br # $_ENV['APP_LANG'] will be 'pt-br'
APP_LANG= # $_ENV['APP_LANG'] will fallback to 'en-us'
```

- `trim`:Just trims the string before set to env vars

```
# .env.example
WHITE_SPACES=trim
# .env
WHITE_SPACES=   string_that_should_be_trimmed #will trim left and right trailling white spaces
```

### important:

[](#important)

Order of validators are mandatory. They will run sequentially, passing the resulting value to the next validator, in a middleware mode. In case validator evaluates to invalid, the pipeline will be interrupted

Custom validators
-----------------

[](#custom-validators)

You can create custom validators and feed Dotenvy with an array with key:value function name, function ref. Rules:

- Validators must be functions with the following signature:

```
function (string $key, string $value, array $args)
```

- You must always return a string that will be passed to next validator in validator chain/pipeline. If you pass null or empty string, the value will be ignored.
- If you want to invalidate the value, you must throw an exception and tell the user what happened.

```
$options = [
  'custom_validators' => [
    'uppercase' => function (string $key, string $value, array $args) {
      return strtoupper($value);
    },
    'lowercase' => function (string $key, string $value, array $args) {
      return strtolower($value);
    },
    'throw_exception' => function (string $key, string $value, array $args) {
      throw new Exception(sprintf('%s=%s %s', $key, $value, implode(' - ', $args)));
    }
  ]
];

$dotenvy = new \Dotenvy\Dotenvy(__DIR__, $options);
```

Reference your validator in `.env.example`

```
#.env.example
MY_ENV_VAR=my_custom_validator_name(my_custom_parameter)
ANOTHER_ENV_VAR=uppercase
```

```
#.env
ANOTHER_ENV_VAR=this_value_will_be_uppercased #will evaluate to THIS_VALUE_WILL_BE_UPPERCASED
```

Usage
=====

[](#usage)

```
$dotenvy = new \Dotenvy\Dotenvy(__DIR__); //directory of containing files (.env and .env.example)

$environment = $dotenvy->execute();
if (is_string($environment)) throw new Exception('Invalid env: ' . $environment);

var_dump($environment);
```

Environment Results
===================

[](#environment-results)

After running Dotenvy, environment variables will be available through:

- `$_SERVER`
- `$_ENV`
- `getenv()`
- `apache_getenv()`

### Important

[](#important-1)

Order of values precedence:

- `$_SERVER`
- `$_ENV`
- `getenv()`
- `apache_getenv()`
- `.env` file
- fallback validator
- throw exception

Performance Optimization
========================

[](#performance-optimization)

Dotenvy can use a compiled cache file for maximum performance. The following code can be used to boost performance in production mode:

```
$envoptions = array();
$dotenvy = new \Dotenvy\Dotenvy(__DIR__, $options);

$is_production = TRUE; //my custom logic to get info about production mode

if ($is_production) {
  if ($dotenvy->hasCacheFile()) {
    $dotenvy->executeFromCache();
  } else {
    $envresult = $dotenvy->execute();
    if (is_array($envresult)) {
      $dotenvy->writeCache($envresult);
    } else {
      throw new \Exception($envresult);
    }
  }
} else {
  //not in production mode
  //delete cache file if exist
  $dotenvy->clearCache();
  $dotenvy->execute();
}
```

### Options usage

[](#options-usage)

```
$envoptions = [
  'example' => '.env.example',
  'envfile' => '.env',
  'allow_ovewrite' => FALSE,
  'cachefile' => md5(date("Ymd")) . '.env',
  'custom_validators' => [
    'mycustomvalidator' => function (string $key, string $value, array $args) {
      return '(-' . $value . '-)';
    }
  ]
];

if ((array_key_exists('CI_ENV', $_SERVER) && $_SERVER['CI_ENV'] === 'production')) {
  Dotenvy\Dotenvy::exec_production(__DIR__, $envoptions);
} else {
  Dotenvy\Dotenvy::exec_development(__DIR__, $envoptions);
}
```

Run tests
=========

[](#run-tests)

```
cd tests && php index.php

```

contributing
============

[](#contributing)

// todo: Fork and make pull requests.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~175 days

Recently: every ~263 days

Total

7

Last Release

1262d ago

PHP version history (2 changes)v0.0.1PHP ^5.5.9 || ^7.0

v0.0.8PHP &gt;=8.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/78198bb487037153950b7247cac44ad35317ce4489e669c3c5ca381386b106a1?d=identicon)[jpolvora](/maintainers/jpolvora)

---

Top Contributors

[![jpolvora](https://avatars.githubusercontent.com/u/955554?v=4)](https://github.com/jpolvora "jpolvora (10 commits)")

### Embed Badge

![Health badge](/badges/jpolvora-dotenvy/health.svg)

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

PHPackages © 2026

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