简体   繁体   English

在请求期间访问新的 Laravel 配置文件

[英]Accessing new Laravel config files during request

I have a scenario where Laravel config files are created and accessed during the same incoming request.我有一个场景,其中在同一个传入请求期间创建和访问 Laravel 配置文件。 However, when accessing the new stored config file's values, config() is unable to access the file's keys/values.但是,当访问新存储的配置文件的值时, config()无法访问文件的键/值。

Here is an example scenario:这是一个示例场景:


public function create(Request $request)
{
    $settings = ['foo' => 'bar'];
    // Store the config.
    Storage::disk('config')->put("settings.php", '<?php return ' . var_export($settings, true) . ';');
    // Results in an error, value not found.
    $config_value = config('settings.foo'); 
}

Is there a way to re-register Laravel config files during a runtime?有没有办法在运行时重新注册 Laravel 配置文件?

Saving contents to the php file config/settings.php is (obviously) not the best way to do it.将内容保存到 php 文件config/settings.php (显然)不是最好的方法。

Either save the config to a database, or simply use the config() helper to assign the values like this:将配置保存到数据库中,或者简单地使用config()助手来分配如下值:

class MyConfigProvider extends ServiceProvider
{
    public function boot() {
        $this->app->booted(function () {
            // This will set the config setting `config/settings.php['app_name']` at runtime:
            config([
                'settings.app_name' => 'My App Name'
            ]);
        });
    }
}

Then, make sure to load this service provider as early in the stack as possible in your config/app.php['providers'] array.然后,确保在config/app.php['providers']数组中尽早在堆栈中加载此服务提供程序。 Basically it overwrites any predefined config that you have set in config/settings.php .基本上它会覆盖您在config/settings.php中设置的任何预定义配置。 You can even retrieve values here from the request object or your database.您甚至可以从请求 object 或您的数据库中检索值。

Yes there is a method for that:是的,有一种方法:

config()->set('settings.foo', $somethingNew);

and then you can read it normally with:然后你可以正常阅读:

$config_value = config('settings.foo'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM