我正在使用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库(红宝石)相比有所不同
我可以轻松解决此问题,但不是很好的解决方案:
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的推荐方法。看来,在不久的将来它不会改变。项目的问题追踪器中的相关讨论: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');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句