这个文件在调用 artisan config:cache 时候是会缓存的,如果需要动态配置 config 相关数据,可以在 ServiceProvider 中调用 config 函数动态配置,不知这样可否满足要求?
先用 env('xxx')
和 config('xxx')
查看是否不一样判断是哪里的问题, 然后再去进行下一步
我记得在 Laravel 中是可以把配置缓存起来的,也可以缓存路由,清理下缓存试试看把
执行这个 php artisan
命令,看看都是什么功能
动态配置在AppServiceProvider.php的boot方法中加载就行了啥
配置保存在数据库中,加载时用缓存读取后转到config中
//试例在AppServiceProvider中的boot加入以下代码
$configs = DB::table('config')->pluck('value','key');
foreach($configs as $key=>$value){
config([$key=> $value]);
}
为了减少数据库查询
$configs = DB::table(‘config’)->pluck(‘value’,’key’);这个应换成缓存,当数据表有增删改时删除缓存就行,
在程序任意地方调用就是
config($key);//假如有一个key为web_name;调用就是config(‘web_name’)
这三个项目可供参考:
提供一个简单的方案。
定义:
public function modify($data)
{
$contentArray = collect(file(base_path('.env'), FILE_IGNORE_NEW_LINES));
$contentArray->transform(function ($item) use ($data) {
foreach ($data as $key => $value) {
$itemArr = explode('=', $item);
if ($itemArr[0] == $key) {
return $key . '=' . $this->format($value);
}
}
return $item;
});
File::put(base_path('.env'), implode(PHP_EOL, $contentArray->toArray()));
}
private function format($value)
{
if (str_contains($value, ' ') || str_contains($value, '$')) {
$value = "\"$value\"";
}
return $value;
}
使用:
modify(['APP_NAME' => 'Laravel 9.0'])
function modifyEnv($timeZone='Europe/Berlin') { $data=[]; if(empty($timeZone)){ $timeZone='Europe/Berlin'; } $data['APP_TIMEZONE']=$timeZone;
$envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
$contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
if('APP_TIMEZONE='.$timeZone != $contentArray->toArray()[5]){
$contentArray->transform(function ($item) use ($data){
foreach ($data as $key => $value){
if(str_contains($item, $key)){
return $key . '=' . $value;
}
}
return $item;
});
if(count($contentArray->toArray())>0){
$content = implode($contentArray->toArray(), "\n");
\Illuminate\Support\Facades\File::put($envPath, $content);
}
}
}
public function updateEnv($key, $newValue, $delim='')
{
$path = base_path('.env');
$oldValue = env($key);
if ($oldValue === $newValue) {
return;
}
if (file_exists($path)) {
file_put_contents(
$path, str_replace(
$key.'='.$delim.$oldValue.$delim,
$key.'='.$delim.$newValue.$delim,
file_get_contents($path)
)
);
}
}
可参考 php artisan key:generate 这个命令里的代码: vendor\laravel\framework\src\Illuminate\Foundation\Console\KeyGenerateCommand.php
/**
* Write a new environment file with the given key.
*
* @param string $key
* @return void
*/
protected function writeNewEnvironmentFileWith($key)
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
$this->keyReplacementPattern(),
'APP_KEY='.$key,
file_get_contents($this->laravel->environmentFilePath())
));
}
/**
* Get a regex pattern that will match env APP_KEY with any random key.
*
* @return string
*/
protected function keyReplacementPattern()
{
$escaped = preg_quote('='.$this->laravel['config']['app.key'], '/');
return "/^APP_KEY{$escaped}/m";
}
推荐文章: