dotenv需要.env文件进行制作

时间:2015-06-04 13:37:41

标签: php environment-variables production-environment laravel-dotenv

我使用dotenv for PHP来管理环境设置(不是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();
}

3 个答案:

答案 0 :(得分:9)

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');

答案 1 :(得分:2)

如果您在创建APP_ENV变量时遇到问题,则此代码更容易:

$dotenv = new Dotenv\Dotenv(__DIR__);
if(file_exists(".env")) {
    $dotenv->load();
}

答案 2 :(得分:1)

另外,我目前的解决方案是使用Lumen's way(截至2016年6月6日)suggested in a discussion

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

如果需要,您仍然可以执行一些额外的异常处理(例如,降至默认值或进行一些验证。

相关问题