在laravel中,可用“php artisan config:clear”语句清除config缓存,解决env获取不到数据的问题;该问题产生的原因是缓存配置文件通过env函数读取环境变量,可能会导致该读取不到环境变量,返回null。
然后我去翻了一下文档,发现其实在 laravel 的 5.2 升级日志中有这么一段:
If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.
让我们看看Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables 的 bootstrap 方法
从 代码我们可以发现,一旦缓存了配置以后,就不会再从 .env 文件加载内容了,所以你在业务代码中使用 env 函数时已经无法读取 .env 中设定的内容了,但是其它环境变量不影响哦。那为啥配置文件的可以呢?因为配置文件缓存的时候会加载 .env 然后读取值缓存配置内容。
那怎么办呢?上面的说明已经告诉我们了:在配置文件创建对应的配置项,比如我们第三方服务可以放到 config/services.php 中,在配置里使用 env 读取,然后把从 env 函数读取的地方改成 config('services.juhe.app_key') 这样来避免这个问题。
其实作者这样做是有道理的,毕竟 .env 文件是文本内容,解析它的成本还是挺高的。