Laravel动态配置设置 [英] Laravel dynamic config settings
问题描述
我在项目中使用了一个程序包,它在config/packagename
I'm using a package within my project and it stores a setting inside config/packagename
我想在配置文件中动态更改此值,这是当前文件结构的样子;
I would like to dynamically change this value inside the config file, this is how the file structure looks currently;
<?php
return [
'view_id' => '118754561',
'cache_lifetime_in_minutes' => 60 * 24,
];
我想将其更改为这样的内容-
I would like to change it to something like this -
'view_id' => Auth::user()->id,
您可以在配置文件中执行此操作,还是必须存储某种变量以便稍后在控制器中进行更新.有没有办法将这些变量放在环境文件中并从控制器访问这些新变量?
Can you do this within the config file, or do you have to store some sort of variable to be updated later within a controller. Is there a way to place these variables in an env file and access these new variables from a controller?
推荐答案
这也是动态更新.env文件的通用解决方案(分别针对各个键/值对)
This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)
- 像这样更改您的config/packagename中的设置:
return [
'view_id' => env('VIEW_ID', '118754561'),
etc...
]
-
向.env中添加一个初始值:
Add an initial value into .env:
VIEW_ID = 118754561
VIEW_ID=118754561
在适当的控制器(例如AuthController)中,使用下面的代码并按如下所示调用函数:
updateDotEnv('VIEW_ID', Auth::User()->id)
In an appropriate controller (e.g. AuthController), use the code below and call the function like this:
updateDotEnv('VIEW_ID', Auth::User()->id)
protected function updateDotEnv($key, $newValue, $delim='')
{
$path = base_path('.env');
// get old value from current env
$oldValue = env($key);
// was there any change?
if ($oldValue === $newValue) {
return;
}
// rewrite file content with changed data
if (file_exists($path)) {
// replace current value with new value
file_put_contents(
$path, str_replace(
$key.'='.$delim.$oldValue.$delim,
$key.'='.$delim.$newValue.$delim,
file_get_contents($path)
)
);
}
}
(如果要使此函数更通用,以便与.env中的key = value对配合使用,则需要使用$ delim参数,其中值必须包含在双引号中,因为它们包含空格).
(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).
诚然,如果您同时有多个用户在项目中使用此软件包,那么这可能不是一个好的解决方案.因此,这取决于您使用此软件包的目的.
Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.
注意:如果您打算从其他类中使用该函数,则当然需要将该函数公开.
NB: You need to make the function public of course if you plan to use it from other classes.
这篇关于Laravel动态配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!