Laravel 自定义配置信息的存储方式
如何修改laravel从文件读取配置的方式
1. 思路
laravel里面的config方法实际上是 调用 \Illuminate\Config\Repository 的get 或者 set方法。那么只能操作Repository实体就够了。这里再次体会到了容器的灵活性,不侵入业务代码依然可以浪。
2. 重新设置config的依赖
- 假如要写死配置信息
//加载自定义的配置信息
$app->singleton('config', function () {
return new \Illuminate\Config\Repository([
"app" => [ "name" => "lv" ]
]);
- 假如要从redis读取配置信息
//加载自定义的配置信息
$app->singleton('config', function () {
//Environment对象自己去实现,load()方法返回配置数组就好。
return new \Illuminate\Config\Repository((new \App\Tool\Config\Environment())->load());;
实现Environment
<?php
namespace App\Tool\Config;
class Environment
{
public function load()
{
$cacheKey = "xxxxxxx";
//假装这是redis
$cache = new Cache();
//1. 从redis中获取
$string = $cache->get($cacheKey);
$environment = json_decode($string, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return [];
}
return $environment;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接