php Laravel 动态配置设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39563042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:56:59  来源:igfitidea点击:

Laravel dynamic config settings

phplaravellaravel-5laravel-5.2

提问by Courtney Ball

I'm using a package within my project and it stores a setting inside config/packagename

我在我的项目中使用了一个包,它在里面存储了一个设置 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 文件中并从控制器访问这些新变量?

回答by matthiku

This also is a generic solution to dynamically update your .env file(respective the individual key/value pairs)

这也是动态更新您的 .env 文件通用解决方案(分别是各个键/值对)

  1. Change the setting in your config/packagename like so:
  1. 像这样更改 config/packagename 中的设置:
return [
    'view_id' => env('VIEW_ID', '118754561'),
    etc...
]
return [
    'view_id' => env('VIEW_ID', '118754561'),
    etc...
]
  1. Add an initial value into .env:

    VIEW_ID=118754561

  2. 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)
                )
            );
        }
    }
    
  1. 将初始值添加到 .env 中:

    VIEW_ID=118754561

  2. 在适当的控制器(例如 AuthController)中,使用下面的代码并像这样调用函数: 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)
                )
            );
        }
    }
    

(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).

(如果您想让此函数更通用,以便使用 .env 中的 key=value 对,其中值必须用双引号括起来,因为它们包含空格,则需要 $delim 参数)。

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.

注意:如果您打算从其他类中使用它,当然需要将该函数公开。

回答by Naresh Kumar P

All configuration files of Laravel framework stored in the app/configdirectory.

Laravel 框架的所有配置文件都存放在该app/config目录中。

so if we need to create custom configuration values it would be better to keep separate our custom configuration in custom file. so we need to create custom file in app/config directory.

因此,如果我们需要创建自定义配置值,最好在自定义文件中单独保留我们的自定义配置。所以我们需要在app/config directory.

Laravel auto read this file as a config file and will auto manage it In this topic we are working with custom configuration in laravel and get configuration value in controller or view.

Laravel 自动读取这个文件作为配置文件并自动管理它在本主题中,我们正在 Laravel 中使用自定义配置并在控制器或视图中获取配置值。

Now i am going to explain how to create a custom config file in Laravel so that we can implement dynamic feature over to this.

现在我将解释如何在 Laravel 中创建自定义配置文件,以便我们可以为此实现动态功能。

create a file in app/config/custom.phpwhich have config keys and value like:-

创建一个文件,app/config/custom.php其中包含配置键和值,例如:-

return array(
  'my_val' => 'mysinglelue',
  'my_arr_val' => array('1', '2', '3'),
);

Now need to get these config values in view/controller so we will use Config class get()method for this

现在需要在视图/控制器中获取这些配置值,因此我们将get()为此使用 Config 类方法

Syntax:

句法:

echo Config::get('filename.arraykey');

where filenameis the config file's name, custom in our case, and key is the array keyof the value you're wanting to access.

这里filenameconfig file's name,风俗在我们的情况下,和关键是array key你想访问的价值。

In Our case it will be as:

在我们的例子中,它将是:

echo Config::get('custom.my_val');

Create run time configuration in laravel :-

在 laravel 中创建运行时配置:-

Configuration values which are set at run-time are will set for the current request, not be carried over to subsequent requests.

在运行时设置的配置值将为当前请求设置,不会传递到后续请求。

You can pass the dynamic values over here so that you can modify the config file dynamically over here using the isset()functions.

您可以在此处传递动态值,以便您可以在此处使用isset()函数动态修改配置文件。

Like how the @Kundan roy as suggested using of the isset()the same condition applies here to. But this one is the alternative method that will work for the dynamic setting of the values in the config.

就像建议使用isset()相同条件的@Kundan roy在这里适用一样。但这是一种替代方法,适用于配置中值的动态设置。

Config::set('custom.my_val', 'mysinglelue');

Hence by using this method you can create the dynamic config files based on the values that you need.

因此,通过使用此方法,您可以根据需要的值创建动态配置文件。

回答by alepeino

If you want to actually edit the config files (either config/packagename.phpor .env) then you may follow matthiku's answer.

如果您想实际编辑配置文件(config/packagename.php.env),那么您可以按照matthiku 的回答进行操作

However, if I were you, I guess I'd rather want to configure this 3rd party package based on some value defined at runtime, instead of modifying any file (which by the way won't take effect until the next request, when the env values are read again).

但是,如果我是你,我想我更愿意根据运行时定义的某个值来配置这个 3rd 方包,而不是修改任何文件(顺便说一下,直到下一个请求才会生效,当env 值被再次读取)。

So, in my opinion the cleanest way to do this is:

所以,在我看来,最干净的方法是:

  • store your desired value in the config data:

    config(['packagename.view_id' => Auth::user()->id]);

  • However, you may notice this probably won't work: the service provider which provides the service you need is often registered before the request is processed, that is, before your config change takes place. So you are still getting the service with old values config.

  • So, how could you have the service provider be called only when needed and not before (that is, after setting the new config value)? You could make it a deferredprovider. Following your example of "spatie laravel-analytics", replace in config/app.phpthis line:

    Spatie\Analytics\AnalyticsServiceProvider::class

    with this one:

    App\Providers\AnalyticsDeferredServiceProvider::class

    and finally create the App\Providers\AnalyticsDeferredServiceProviderclass, with:

  • 将您想要的值存储在配置数据中:

    config(['packagename.view_id' => Auth::user()->id]);

  • 但是,您可能会注意到这可能行不通:提供您需要的服务的服务提供者通常在处理请求之前注册,即在您的配置更改发生之前。因此,您仍然使用旧值配置获得服务。

  • 那么,如何让服务提供者仅在需要时而不是之前(即在设置新配置值之后)才被调用?您可以将其设为延期提供者。按照您的“spatie laravel-analytics”示例,在config/app.php这一行中替换:

    Spatie\Analytics\AnalyticsServiceProvider::class

    有了这个:

    App\Providers\AnalyticsDeferredServiceProvider::class

    最后创建App\Providers\AnalyticsDeferredServiceProvider类,使用:

:

<?php
namespace App\Providers;

use Spatie\Analytics\Analytics;
use Spatie\Analytics\AnalyticsServiceProvider;

class AnalyticsDeferredServiceProvider extends AnalyticsServiceProvider
{
    protected $defer = true;

    public function provides()
    {
        return [Analytics::class];
    }
}

This way you can have the provider read the config values when you are about to instantiate the service, after you set any runtime config values.

通过这种方式,您可以在设置任何运行时配置值后,在您准备实例化服务时让提供程序读取配置值。

回答by Shahid Chaudhary

Use this in controller when you need to change.

当您需要更改时,在控制器中使用它。

  <?php

    use Illuminate\Support\Facades\Config;

     //[...]

    $user_id =  Auth::user()->id; 

    Config::set('view_id', $user_id );

回答by Kundan roy

You can do like this.

你可以这样做。

In your custom config file. Add the following code You can send your id dynamically from the query string.

在您的自定义配置文件中。添加以下代码您可以从查询字符串动态发送您的 id。

'view_id' => isset($_REQUEST['view_id'])?$_REQUEST['view_id']:null,

To get view id

获取视图 ID

 echo config('app.view_id'); // app is config file name

回答by Kundan roy

config(['packagename.view_id' => Auth::user()->id]);

config(['packagename.view_id' => Auth::user()->id]);

回答by lasec0203

Since Laravel v5.2 you can dynamically set config values this way:

从 Laravel v5.2 开始,您可以通过这种方式动态设置配置值:

<?php

config(['app.timezone' => 'America/Chicago']);

$value = config('app.timezone');

echo $value;
// output: 'America/Chicago'

回答by Saumya Rastogi

Actually if you are that point of code which forces you to make the config values dynamic, then there should be something wrong with your code flow, as the use of config file is just for initializing required values - which should be defined before the app is loaded.

实际上,如果您是强制您使配置值动态化的代码点,那么您的代码流应该有问题,因为配置文件的使用仅用于初始化所需的值 - 应该在应用程序之前定义加载。

Making config values dynamic is a "BAD PRACTICE"in the world of coding. So there is the following alternative for your problem.

使配置值动态化是编码世界中的“不良做法。因此,您的问题有以下替代方案。

Define value in .env file(optional)

在 .env 文件中定义值(可选)

VIEW_ID=your_view_id_here

Use value inside Controller

在控制器中使用值

$auth_id = auth()->user()->id;
$view_id = env('VIEW_ID', $auth_id);
// If .env file doesn't contains 'VIEW_ID' it will take $auth_user as the view_id

Hope this helps you!

希望这对你有帮助!