【发布时间】:2015-08-19 03:39:20
【问题描述】:
我在 PHP 中使用 dotenv 来管理环境设置(不是 lavarel,但我标记了它,因为 lavarel 也使用 dotenv)
我已将 .env 从代码库中排除,并为所有其他合作者添加了 .env.example
dotenv的github页面上:
phpdotenv 是为开发环境而设计的,一般不应该在生产环境中使用。在生产环境中,应该设置实际的环境变量,这样就不会在每个请求上加载 .env 文件的开销。这可以通过使用 Vagrant、chef 或 Puppet 等工具的自动化部署过程来实现,也可以使用 Pagodabox 和 Heroku 等云主机手动设置。
我不明白的是,我得到了以下异常:
PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Dotenv: Environment file .env not found or not readable.
这与文档中所说的“应设置实际的环境变量,以便在每个请求上没有加载 .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();
}
【问题讨论】:
-
如果你不在生产服务器上使用 .env ,那么你如何设置你的环境变量呢?
标签: php environment-variables production-environment phpdotenv