簡體   English   中英

Yii2組件類在實例化時未加載配置

[英]Yii2 Component class not loading config when instantiated

我創建了一個簡單的自定義Component,它從yii\\base\\Component擴展。

namespace app\components\managers;

use yii\base\Component;
use yii\base\InvalidConfigException;

class HubspotDataManager extends Component
{
    public $hubspotApiKey;

    private $apiFactory;

    public function init()
    {
        if (empty($this->hubspotApiKey)) {
            throw new InvalidConfigException('Hubspot API Key cannot be empty.');
        }

        parent::init();

        // initialise Hubspot factory instance after configuration is applied
        $this->apiFactory = $this->getHubspotApiFactoryInstance();
    }

    public function getHubspotApiFactoryInstance()
    {
        return new \SevenShores\Hubspot\Factory([
            'key' => $this->hubspotApiKey,
            'oauth' => false, // default
            'base_url' => 'https://api.hubapi.com' // default
        ]);
    }
}

我已經在config/web.php應用程序配置中注冊了該組件,在其中我還添加了一個自定義參數。

'components' => [
    ...
    'hubspotDataManager' => [
        'class' => app\components\managers\HubspotDataManager::class,
        'hubspotApiKey' => 'mycustomkeystringhere',
    ],
    ...
],

但是,我發現像這樣實例化組件時:

$hubspot = new HubspotDataManager();

hubspotApiKey配置參數不傳遞到__construct($config = []) - $config僅僅是一個空數組,所以在init()的配置不設置部件hubspotApiKey屬性的值hubspotApiKey在配置,所以因此,我從拋出的異常中看到了這一點:

無效的配置– yii \\ base \\ InvalidConfigException

Hubspot API密鑰不能為空。

但是,如果我這樣調用該組件:

Yii::$app->hubspotDataManager

它確實傳遞了這個配置變量! 為什么是這樣? 我必須做些什么額外的工作才能使組件加載其應用程序配置數據以進行標准類實例化? 我在文檔中找不到有關此特定方案的任何信息。

注意:使用基本的應用程序模板使用最新的Yii2版本2.0.15.1

在不使用服務定位器創建實例時,配置當然是未知的。

流程是這樣的, Yii::$app是一個服務定位器。 它將配置傳遞給Dependency Injector Yii::$container

如果要不使用Service Locator Yii::$app來傳遞配置,則可以設置容器:

Yii::$container->set(app\components\managers\HubspotDataManager::class, [
    'hubspotApiKey' => 'mycustomkeystringhere',
]);

$hubspot = Yii::$container->get(app\components\managers\HubspotDataManager::class); 

結果將與使用服務定位器Yii::$app

您還可以像這樣實例化該類的新實例,並將配置傳遞給它。

$hubspot = new HubspotDataManager([
    'hubspotApiKey' => 'mycustomkeystringhere',
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM