prinx/dotenv

简化应用程序中环境变量的访问

v1.0.0 2021-05-22 14:41 UTC

This package is auto-updated.

Last update: 2024-09-22 22:16:34 UTC


README

PHP Dotenv

tests codecov

轻松访问环境变量。

安装

在项目根目录下打开命令提示符并运行

composer require prinx/dotenv

用法

快速入门

// Require composer autoload file if it has not been done yet.
require_once __DIR__ . '/path/to/vendor/autoload.php';

/*
 * Retrieve an environment variable. Returns null if variable not found.
 */
$hostname = env('DEV_DB_HOST');

/*
 * Retrieve an environment variable. Returns default value passed as second argument if variable not found
 */
$port = env('DEV_DB_PORT', 3306);

/*
 * Add a variable to the current loaded environment (will not save in the .env file)
 */
addenv('LOG_LEVEL', 'info');

/*
 * Wrtie variable to the env file. 
 * Will also automatically load the variable into the current environment.
 * If the file already contains the variable, the variable will be overwritten.
 */
persistenv('LOG_LEVEL', 'warn');
persistenv('LOG_LEVEL', 'debug');
persistenv('LOG_LEVEL', 'info');

/*
 * Get all environment variables
 */
env()
// OR
allenv();

编写 .env 文件

.env 文件格式为

VARIABLE_NAME=value

例如

SESSION_DRIVER=file
DEV_DB_HOST=localhost
DEV_DB_PORT=3306

PROD_DB_HOST=prod_db_ip
PROD_DB_PORT=3308 

默认情况下,变量名以大写字母开头,单词之间用下划线分隔。

注释

您可以通过在注释前加上哈希符号(#)在 .env 文件中写入注释。例如

# Supported: file|database
SESSION_DRIVER=file

值的类型

默认情况下,环境变量将作为字符串检索,除非是布尔值或 null。

字符串

您可以使用引号将字符串包围。

APP_NAME=My app
# or
APP_NAME="My app"

DB_HOST=173.0.0.0
# or
DB_HOST="173.0.0.0"
布尔值

true"true"'true' 将作为布尔值 true 检索。值 false"false"'false' 将作为布尔值 false 检索。

# Will be got as a boolean true
APP_DEBUG=true

# Will be got as a boolean false
APP_DEBUG=false

相同于

APP_DEBUG="true"

APP_DEBUG="false"
空值

null"null"'null' 将作为 null 检索。

# Will be got as a null
APP_DEBUG=null

APP_DEBUG="null"

引用另一个变量

您可以通过将您要引用的变量的名称放在 ${} 内来在 .env 文件中引用另一个变量的值

# .env
SESSION_DRIVER=mysql
MESSAGE=App based on ${SESSION_DRIVER} database
// PHP
echo env('MESSAGE'); // App based on mysql database

加载特定的 .env 文件

默认情况下,该包会自动在项目根目录中查找 .env 文件。但您可以使用 loadenv 函数从任何位置加载 env 文件

// Require composer autoload file if it has not been done yet.
require_once __DIR__ . '/path/to/vendor/autoload.php';

loadenv('/path/to/somewhere/.env');

// Then everything goes as usual
$apiKey = env('API_KEY');

使用 Dotenv 实例

您还可以使用 Dotenv 类实例获取或设置变量

可以通过调用 dotenv() 函数来访问 Dotenv 实例

$dotenv = dotenv();

获取变量

$hostname = dotenv()->get('DEV_DB_HOST');

// With a default value
$hostname = dotenv()->get('DEV_DB_HOST', 'localhost');

获取所有变量

$hostname = dotenv()->all();

// or use get without any parameter
$hostname = dotenv()->get();

将变量添加到当前加载的环境

dotenv()->add('GUEST_NAME', 'john');

将变量写入 .env 文件

dotenv()->persist('GUEST_NAME', 'john');

创建自己的 Dotenv 实例

您只需使用 Dotenv 类即可创建自己的 Dotenv 实例

use Prinx\Dotenv;

$dotenv = new Dotenv('path/to/.env');

$dotenv->get('VARIABLE');

贡献

  • 给仓库加星标 ☺️
  • 分支仓库。
  • 修复错误,添加新功能。
  • 编写测试。
  • 创建拉取请求。

许可协议

MIT