nexus633/processenv

解析 .env 文件,自动将变量加载到 $_ENV 和/或 $_SERVER

v1.0.1 2023-10-23 00:00 UTC

This package is auto-updated.

Last update: 2024-09-08 00:14:39 UTC


README

在您的项目中使用 .env 文件

使用 Processenv,您有机会直接在项目中使用环境变量。
您可以解析 .env 文件并将它们添加到超级全局变量 $_ENV$_SERVER 中。
您还可以使用 Processenv 指定默认值。如果没有环境变量,将使用这些值。
这使得检查错误和使用标准配置变得更加容易。

您还可以在环境文件中定义嵌套变量、数组和对象
您可以使用内联注释和掩码井号(\#)

版本 1.0.1

查看 变更日志

安装

$ composer require nexus633/processenv

用法

<?php

require 'vendor/autoload.php';
use Nexus633\Processenv\Processenv;

$env = new Processenv();
$env->load();
<?php

require 'vendor/autoload.php';
use Nexus633\Processenv\Processenv;

/**
 * with options
 * the options in this example are the default values 
 */

$env = new Processenv(
    new ProcessenvOptions(
        localFirst: true,
        exceptions: true,
        globalEnv: false,
        globalServer: false,
        globalKey: false,
        objectParser: self::PARSE_AS_STDCLASS,
        replacePattern: '[:PROCESSENV_REPLACE:]'
    )
);

$env->load();

选项

如果此选项设置为 true,则从 .env 文件设置的环境变量将作为第一个元素添加到 $_ENV 之前。

   localFirst = true

如果此选项设置为 true,则在没有 .env 文件的情况下抛出 FileNotFoundException,否则仅反映 $_ENV 的超级全局值。

   exceptions = true

如果此选项设置为 true,则从 .env 文件添加环境变量到超级全局变量 $_ENV。

   globalEnv = true

如果此选项设置为 true,则从 .env 文件添加环境变量到超级全局变量 $_SERVER。

   globalServer = true

当此选项设置为 true 时,在超级全局变量 $_ENV 中添加一个新的键名为 DOTENV。该键包含 .env 文件中的变量

   globalKey = true

如果选项设置为“ProcessenvOptions::PARSE_AS_STDCLASS”,则 .env 文件中的对象将自动转换为 StdClass。
如果选项设置为 ProcessenvOptions::PARSE_AS_ARRAY,则对象将被转换为关联数组

    objectParser = ProcessenvOptions::PARSE_AS_STDCLASS | ProcessenvOptions::PARSE_AS_ARRAY

使用此选项可以指定如何解析掩码注释。

    replacePattern = '[:PROCESSENV_REPLACE:]'

获取环境变量

# this .env file is a example
MODE=live
IGNORED=${HOME_PATH}
HOME_PATH=/var/www
LOG_PATH=${HOME_PATH}/log
ACCESS_LOG='${LOG_PATH}/access.log'
ERROR_LOG=${LOG_PATH}/error.log
ERROR_MODE='{ "info": "${LOG_PATH}/info.log", "fatal": "${LOG_PATH}/fatal.log", "exception": "${LOG_PATH}/exception.log" }'
ERROR_MODE_ARRAY='[ "info\\#with masked hash", "fatal", "exception" ]'
INLINE_COMMENT='this is a inline comment #not parsed'
INLINE_COMMENT_WITH_ESCAPE='this is an inline comment \# with masked hash'
<?php

echo $env->processenv('LOG_PATH');
/* if HOME_PATH is set then the result is `(string) /var/www/log` else empty string */

echo $env->processenv('LOG_PATH', '/var/www/log');
/* if HOME_PATH is set then the result is `(string) /var/www/log` else `(string) /var/www/log` as fallback value */

echo $env->processenv('INLINE_COMMENT');
/* output: this is an inline comment */

echo $env->processenv('INLINE_COMMENT_WITH_ESCAPE');
/* output: this is an inline comment # with masked hash */

print_r($env->processenv());
/* get all environment variables */

使用魔法方法

<?php

echo $env->HOME_PATH;
// if HOME_PATH is set, then the result is `(string) /var/www/log` else empty string

END

发现了建议或错误吗?请发起拉取请求或提问 :-)