PHPackages                             dev-macb/ambivar - 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. dev-macb/ambivar

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

dev-macb/ambivar
================

O Ambivar é um pacote em PHP que tem como objetivo facilitar a gestão de variáveis de ambiente em seus projetos.

1.2.0(2y ago)028MITPHPPHP &gt;=7.0

Since Mar 23Pushed 1y ago1 watchersCompare

[ Source](https://github.com/dev-macb/ambivar)[ Packagist](https://packagist.org/packages/dev-macb/ambivar)[ RSS](/packages/dev-macb-ambivar/feed)WikiDiscussions main Synced today

READMEChangelog (3)DependenciesVersions (4)Used By (0)

🔷 Ambivar 🔷
===========

[](#-ambivar-)

 [![Packagist Version](https://camo.githubusercontent.com/dd425dd5b498f2a8de1c452b3af4819a8376b54e0524ba0a0b2580da03fcbe91/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179)](https://camo.githubusercontent.com/dd425dd5b498f2a8de1c452b3af4819a8376b54e0524ba0a0b2580da03fcbe91/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179) [![Packagist Downloads](https://camo.githubusercontent.com/e27a9f4e922e3a6dffe10f862a73b9b9df03ae1f35bea90ebc0739499e352f7a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179)](https://camo.githubusercontent.com/e27a9f4e922e3a6dffe10f862a73b9b9df03ae1f35bea90ebc0739499e352f7a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179) [![Packagist License](https://camo.githubusercontent.com/a90851acde05b768ec522e0ae69470847f7b72278556658454f1a1c44cf3f888/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179)](https://camo.githubusercontent.com/a90851acde05b768ec522e0ae69470847f7b72278556658454f1a1c44cf3f888/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6465762d6d6163622f616d62697661723f636f6c6f723d626c7565266c6f676f436f6c6f723d67726179)

🎯 Objetivo
----------

[](#-objetivo)

O **Ambivar** é um pacote em PHP para facilitar a gestão de variáveis de ambiente em projetos. Ele permite carregar e manipular variáveis através de um arquivo `.env`, garantindo segurança e flexibilidade para o gerenciamento de configurações do sistema.

🔷

🔧 Instalação
------------

[](#-instalação)

Para instalar o Ambivar, certifique-se de ter o [PHP](https://www.php.net/) e o [Composer](https://getcomposer.org/) instalados. Execute o seguinte comando:

```
composer require dev-macb/ambivar
```

🔷

🚀 Uso Básico
------------

[](#-uso-básico)

### Carregamento de Variáveis

[](#carregamento-de-variáveis)

```
use MacB\Ambivar;

Ambivar::inicializar(__DIR__);  // Opcional
Ambivar::dotenv();              // Carrega o arquivo .env padrão
Ambivar::carregar(".env.dev");  // Carrega um arquivo específico
```

### Manipulação de Variáveis

[](#manipulação-de-variáveis)

```
Ambivar::adicionar('APP_ENV', 'production');
Ambivar::remover('TEMP_VAR');
$valor = Ambivar::obter('DB_HOST', 'localhost');
```

### Acesso às Variáveis

[](#acesso-às-variáveis)

```
echo Ambivar::obter('DB_NAME');
echo getenv('DB_NAME');
echo $_ENV['DB_NAME'];
```

🔷

📚 Documentação Técnica
----------------------

[](#-documentação-técnica)

#### `ambivar(string $diretorioBase = null): void`

[](#ambivarstring-diretoriobase--null-void)

Define o diretório base para carregar arquivos `.env`.

```
Ambivar::ambivar(__DIR__);
```

#### `dotenv(): bool`

[](#dotenv-bool)

Carrega o arquivo `.env` padrão do diretório base.

```
// Retorna true se o arquivo foi carregado com sucesso
$resultado = Ambivar::dotenv();
```

#### `carregar(string $caminhoDoArquivoEnv): bool`

[](#carregarstring-caminhodoarquivoenv-bool)

Carrega um arquivo `.env` específico.

```
// Carrega um arquivo .env específico
$resultado = Ambivar::carregar('/caminho/completo/.env.production');
```

#### `carregarDiretorio(string $diretorio): int`

[](#carregardiretoriostring-diretorio-int)

Carrega todas as variáveis de ambiente dos arquivos `.env` dentro de um diretório.

```
// Retorna o número de arquivos carregados com sucesso
$contador = Ambivar::carregarDiretorio(__DIR__ . '/environments');
```

#### `existe(string $chave): bool`

[](#existestring-chave-bool)

Verifica se uma variável de ambiente existe.

```
if (Ambivar::existe('SECRET_KEY')) {
    // A variável existe
}
```

#### `obter(string $chave, mixed $padrao = null): mixed`

[](#obterstring-chave-mixed-padrao--null-mixed)

Obtém o valor de uma variável de ambiente ou retorna um valor padrão se não existir.

```
// Obtém APP_DEBUG ou retorna false se não estiver definido
$valor = Ambivar::obter('APP_DEBUG', false);
```

#### `obterTodos(): array`

[](#obtertodos-array)

Retorna todas as variáveis de ambiente carregadas.

```
// Obtém todas as variáveis carregadas
$todasVariaveisDeAmbiente = Ambivar::obterTodas();
```

#### `adicionar(string $chave, string $valor, ?string $caminhoDoArquivoEnv = null): bool`

[](#adicionarstring-chave-string-valor-string-caminhodoarquivoenv--null-bool)

Adiciona ou atualiza uma variável de ambiente.

```
// Define APP_ENV como 'production' no arquivo .env padrão
Ambivar::adicionar('APP_ENV', 'production');

// Define DEBUG como 'true' em um arquivo específico
Ambivar::adicionar('DEBUG', 'true', __DIR__ . '/.env.dev');
```

#### `adicionarVarios(array $variaveis, ?string $caminhoDoArquivoEnv = null): int`

[](#adicionarvariosarray-variaveis-string-caminhodoarquivoenv--null-int)

Adiciona múltiplas variáveis de ambiente de uma só vez.

```
// Define múltiplas variáveis e retorna o número de variáveis definidas com sucesso
$contador = Ambivar::setMany([
    'APP_NAME' => 'Minha Aplicação',
    'APP_ENV' => 'production',
    'APP_DEBUG' => 'false',
    'APP_URL' => 'https://example.com'
]);
```

#### `remover(string $chave, ?string $caminhoDoArquivoEnv = null): bool`

[](#removerstring-chave-string-caminhodoarquivoenv--null-bool)

Remove uma variável de ambiente.

```
// Remove a variável TEMP_TOKEN do arquivo .env padrão
Ambivar::remover('TEMP_TOKEN');

// Remove a variável DEBUG de um arquivo específico
Ambivar::remover('DEBUG', __DIR__ . '/.env.test');
```

### Boas Práticas

[](#boas-práticas)

- **Não commit arquivos `.env`**: Adicione ao `.gitignore` e forneça um `.env.example`.
- **Evite armazenar dados sensíveis em texto puro**.
- **Use nomes descritivos e padrões** (`DB_HOST`, `APP_ENV`).
- **Sempre forneça valores padrão** ao acessar variáveis.

✒️ Contribuições
----------------

[](#️-contribuições)

Se deseja contribuir, relate problemas ou sugira melhorias abrindo uma [Issue](https://github.com/dev-macb/ambivar/issues)ou enviando um *Pull Request*. Se gostou do projeto, deixe uma ⭐ para apoiar!

🔷

📄 Licença
---------

[](#-licença)

O Ambivar é licenciado sob a **MIT License**. Consulte os termos em [LICENSE](https://github.com/dev-macb/ambivar/blob/dev/LICENSE.md).

🔷

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

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 ~62 days

Total

3

Last Release

1075d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6ac9f70f9a1c8f7b285bb8194726b144c24ab7ccc6c923248b87f58b523f2564?d=identicon)[dev-macb](/maintainers/dev-macb)

---

Top Contributors

[![dev-macb](https://avatars.githubusercontent.com/u/107478277?v=4)](https://github.com/dev-macb "dev-macb (55 commits)")

---

Tags

ambivardotenvenvenvironmentenvironment-variablesvariaveis-ambienteenvironmentenvdotenvvariaveisambientevariáveis de ambienteambivar

### Embed Badge

![Health badge](/badges/dev-macb-ambivar/health.svg)

```
[![Health](https://phpackages.com/badges/dev-macb-ambivar/health.svg)](https://phpackages.com/packages/dev-macb-ambivar)
```

###  Alternatives

[vlucas/phpdotenv

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

13.5k640.2M6.3k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k243.3M2.8k](/packages/symfony-dotenv)[diarmuidie/envpopulate

Tool to interactively populate a `.env` file based on an `.env.example` file whenever Composer installs or updates.

1695.7k](/packages/diarmuidie-envpopulate)[zepgram/magento-dotenv

Simple autoloader to integrate the Symfony Dotenv component into Magento2

1376.0k](/packages/zepgram-magento-dotenv)[nystudio107/dotenvy

Speed up your production sites by ditching .env for key/value variable pairs as Apache, Nginx, and shell equivalents.

317.0k](/packages/nystudio107-dotenvy)[dotenv-org/phpdotenv-vault

Load environment variables from encrypted .env.vault files

1019.5k2](/packages/dotenv-org-phpdotenv-vault)

PHPackages © 2026

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