我已经创建了扩展XeroServiceProvide的自定义服务提供商,基本上,我有多个Xero帐户,并且我想更改两个配置参数值运行时 consumer_key 和 consumer_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
答案 0 :(得分:1)
这就是我最终做的。我创建了一个在运行时设置值的自定义函数。
/**
* 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);