如何在 运行 时间绑定配置值 Laravel 服务提供者?

How to bind configuration value Laravel service provider on run-time?

我创建了扩展 XeroServiceProvide 的自定义服务提供商,基本上,我有多个 Xero 帐户,我想更改两个配置参数值运行时 consumer_keyconsumer_secret。有没有快速的方法。我检查了 Service Container 上下文绑定,但不知道如何使用。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use DrawMyAttention\XeroLaravel\Providers\XeroServiceProvider;

class CustomXeroServiceProvider extends XeroServiceProvider
{
    private $config = 'xero/config.php';

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        parent::boot();
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register($configParams = [])
    {
        parent::register();

        if(file_exists(config_path($this->config))) {
            $configPath = config_path($this->config);
            $config = include $configPath;
        }

        $this->app->bind('XeroPrivate', function () use ($config,$configParams) {

            if(is_array($configParams) && count($configParams) > 0){
                if(isset($configParams['consumer_key'])){
                    $config['oauth']['consumer_key']    = $configParams['consumer_key'];
                }

                if(isset($configParams['consumer_secret'])){
                    $config['oauth']['consumer_secret'] = $configParams['consumer_secret'];
                }
            }
            return new \XeroPHP\Application\PrivateApplication($config);
        });

    }
}

我尝试从 Controller 更改值,但绑定参数没有动态更改

foreach($centers as $center) {

 config(['xero.config.oauth.consumer_key' => $center->consumer_key]);
 config(['xero.config.oauth.consumer_secret' => $center->consumer_secret]);
}

更新 2

有没有一种方法可以在更新配置文件值后重新绑定服务容器,或者我可以以某种方式刷新服务提供商绑定?

config(['xero.config.oauth.consumer_key' => 'XXXXXXX']);
config(['xero.config.oauth.consumer_secret' => 'XXXXXX']);
// rebind Service provider after update

这就是我最终的做法。我创建了一个在运行时设置值的自定义函数。

/**
 * connect to XERO by center
 * @param $center
 * @return mixed
 */
public static function bindXeroPrivateApplication($center){
    $configPath = config_path('xero/config.php');
    $config = include $configPath;
    config(['xero.config.oauth.consumer_key' => $center->consumer_key]);
    config(['xero.config.oauth.consumer_secret' => $center->consumer_secret]);

    
    return \App::bind('XeroPrivate', function () use ($config,$center) {
        $config['oauth']['consumer_key']    = $center->consumer_key;
        $config['oauth']['consumer_secret'] = $center->consumer_secret;

        return new \XeroPHP\Application\PrivateApplication($config);
    });
}

我有一个名为 Center.php 的模型,我正在从与下面相同的模型调用上面的函数。

$center = Center::find(1);
self::bindXeroPrivateApplication($center);