San*_*ser 10 php environment-variables production-environment phpdotenv
我正在使用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();
}
Run Code Online (Sandbox Code Playgroud)
在我看来最好的解决方案,但我认为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();
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*lik 11
Dotenv是围绕一个想法构建的,它只会在开发环境中使用.因此,它始终期望.env文件存在.
您不喜欢的解决方案是使用Dotenv的推荐方法.似乎它在不久的将来不会改变.项目问题跟踪器中的相关讨论:https://github.com/vlucas/phpdotenv/issues/63#issuecomment-74561880
请注意,Mark 为生产/暂存环境提供了一种很好的方法,它可以跳过文件加载,但不会验证
$dotenv = new Dotenv\Dotenv();
if(getenv('APP_ENV') === 'development') {
$dotenv->load(__DIR__);
}
$dotenv->required('OTHER_VAR');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20015 次 |
| 最近记录: |