php - dotenv 在生产环境中需要 .env 文件

标签 php environment-variables production-environment phpdotenv

我正在使用 PHP 的 dotenv 来管理环境设置(不是 lavarel,但我标记了它,因为 lavarel 也使用 dotenv)

我已经从代码库中排除了 .env 并为所有其他协作者添加了 .env.example

在dotenv的github页面上:

phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku.

我不明白的是我得到了以下异常:

PHP fatal error :未捕获异常“InvalidArgumentException”,消息为“Dotenv:环境文件 .env 未找到或不可读。”

这与文档中所说的“应该设置实际的环境变量,以便在每次请求时都不会加载 .env 文件的开销”相矛盾。

所以问题是 dotenv 抛出该异常是否有任何原因和/或我是否遗漏了什么?首先,与其他 dotenv 库 (ruby) 相比,行为是不同的

我可以很容易地解决这个问题,不太好的解决方案:

if(getenv('APPLICATION_ENV') !== 'production') { /* or staging */
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
}

我认为最好的解决方案,但我认为 dotenv 应该处理这个问题。

$dotenv = new Dotenv\Dotenv(__DIR__);
//Check if file exists the same way as dotenv does it
//See classes DotEnv\DotEnv and DotEnv\Loader
//$filePath = $dotenv->getFilePath(__DIR__); 
//This method is protected so extract code from method (see below)

$filePath = rtrim(__DIR__, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR . '.env';
//both calls are cached so (almost) no performance loss
if(is_file($filePath) && is_readable($filePath)) {
    $dotenv->load();
}

最佳答案

Dotenv 是围绕一个想法构建的,即它将仅用于开发环境。因此,它总是期望存在 .env 文件。

您不喜欢的解决方案是使用 Dotenv 的推荐方式。看起来,它 won't change in near future 。项目的问题跟踪器中的相关讨论:https://github.com/vlucas/phpdotenv/issues/63#issuecomment-74561880

请注意,Mark offers 有一种用于生产/暂存环境的好方法,它会跳过文件加载,但不会跳过验证

$dotenv = new Dotenv\Dotenv();
if(getenv('APP_ENV') === 'development') {
    $dotenv->load(__DIR__);
}
$dotenv->required('OTHER_VAR');

关于php - dotenv 在生产环境中需要 .env 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645324/

相关文章:

python - 为什么我的环境变量无法加载到我的 Flask 应用程序中?

grails - 是否可以从生产环境中排除 grails 插件?

security - Golang 二进制文件如何以及为何显示有关错误的文件和行信息

java - 在生产中运行 jetty-maven-plugin

php - 在 javascript 中使用 php 函数

php - 获取系统启动时间(不读取/proc/uptime)

php - 这个数据库查询有什么问题?

php - codeigniter 和 MYSQL 中的 Set_relation_n_n grocery crud

java - System.getenv() 和 System.getProperty() 之间的区别

spring-boot - Docker的环境变量未传递给Spring