adhocore/env

- Environment variable loader and retriever for PHP.
- Sanitization/Filters can be applied on retrieval if
filter extension is loaded.
- Using env to configure application is one of the 12 postulates.
Installation
composer require adhocore/env
Usage
Loading
use Ahc\Env\Loader;
(new Loader)->load('/project/root/.env');
(new Loader)->load('/project/root/.env', true);
(new Loader)->load('/project/root/.env', true, Loader::SERVER);
(new Loader)->load('/project/root/.env', true, Loader::ENV | Loader::PUTENV);
(new Loader)->load('/project/root/.env', true, Loader::ALL);
Always wrap complex values within double quotes in .env file. Eg: APP_KEY="K&^¢*&D(?<µ}^(P\]X"
ENV Format
Supports # or ; comments. Literal double quote should be escaped like "". See more examples below:
# comment line
a=1
b="2"
c=$3#
; also comment line
d="lol"
# empty
e=
# f is `"6"`
f=""6""
1_2=one_two
# empty too
E=""
A_B=Apple Ball
x=Y
Reference is possible like so:
MAIN=1
REF=${MAIN}/2
REF2=${REF}/3
# below will not be parsed as INV is not resolved
REF3=${INV}
Retrieving
use Ahc\Env\Retriever;
echo Retriever::getEnv($key);
echo Retriever::getEnv('PAYMENT_GATEWAY', 'stripe');
echo Retriever::getEnv('MYSQL_PORT', 3306, FILTER_VALIDATE_INT);
echo env('THE_KEY');
See filter_var for more on sanitizing/filtering values!
Benchmark
If you are interested here is a simple benchmark.
Consideration
By default this library only loads env to putenv().
Be cautious exposing confidential credentials into $_ENV and $_SERVER which bug/error catchers may log.
Although this libray is already fast enough, in production you might want to boost performance a little by loading if only required:
if (!getenv('<LAST_ENV_APP_SHOULD_BE_AWARE_OF>')) {
(new Loader)->load('/project/root/.env', false);
}
For example if your app last introduced FB_APP_ID env, but this value is not already hard set in the machine,
it would be loaded via .env file else you are already covered.
Credits
This project is release
managed by please.