, (*1)
Simple dotenv for PHP
Introduction
Q: What's the point of this package? How is it any different from those vlucas/phpdotenv and josegonzalez/php-dotenv well-known packages?, (*2)
A: Those great packages are NOT for production. They were always meant to be used during local development only.
The main reasons are:
1) Not fast enough
2) Not secure enough, (*3)
Many people are actually misuse those packages and use them to configure apps in production too., (*4)
In contrast this package IS for production.
It uses plain old php array for .env
content and doesn't touch $_ENV or $_SERVER by default.
As a result it's fast and secure but has less features., (*5)
Installation
1) composer require arrilot/dotenv-php
, (*6)
2) Create .env.php
file to store configuration settings that are environment specific or sensitive., (*7)
Example:, (*8)
<?php
return [
'DB_USER' => 'root',
'DB_PASSWORD' => 'secret',
];
This file should NEVER be added to version control., (*9)
3) Create .env.example.php
file and add it to version control. This file should serve as an example for developers how .env.php
file should look like., (*10)
4) Load .env.php
file, (*11)
use Arrilot\DotEnv\DotEnv;
DotEnv::load('/path/to/.env.php');
Usage
Getting data
The most used case is to get dotenv variable., (*12)
$dbUser = DotEnv::get('DB_USER');
You may pass a second parameter, which is gonna be used as default if variable is not set., (*13)
$dbUser = DotEnv::get('DB_USER', 'admin');
Note
This is the method you are going to use most of the time.
It makes sense to add a global helper for it to avoid importing the class name and e.t.c., (*14)
function env($key, $default = null)
{
return \Arrilot\DotEnv\DotEnv::get($key, $default);
}
...
$dbUser = env('DB_USER', 'admin');
You can also get all dotenv variables at once:, (*15)
$variables = DotEnv::all();
Setting data
You can set or override specific variable like that:, (*16)
DotEnv::set('DB_USER', 'admin');
DotEnv::set('DB_PASSWORD', 'secret');
// or
DotEnv::set([
'DB_USER' => 'root',
'DB_PASSWORD' => 'secret',
]);
You can reload all variables entirely from file or array, (*17)
DotEnv::load('/path/to/new/.env.php');
//or
DotEnv::load([
'DB_USER' => 'root',
'DB_PASSWORD' => 'secret',
]);
Other methods
There is way to ensure that a specific dotenv variable exists.
Example:, (*18)
DotEnv::setRequired(['DB_USER', 'DB_PASSWORD']);
If the variable is not loaded an Arrilot\DotEnv\Exceptions\MissingVariableException
will be thrown., (*19)
There are also convenient methods to copy all variables to putenv()
, $_ENV
or $_SERVER
if you DO need it, but in most cases you don't, (*20)
DotEnv::copyVarsToPutenv($prefix = 'PHP_'); // putenv()
DotEnv::copyVarsToEnv(); // $_ENV
DotEnv::copyVarsToServer() // $_SERVER
Testing
Q: Why are there so many static calls? How am I supposed to mock them in tests?, (*21)
A: You shouldn't mock DotEnv
class. Just override what you need using set
or load
methods.
Note that load
method understands arrays too., (*22)