Yii2 组件 class 实例化时未加载配置

Yii2 Component class not loading config when instantiated

我创建了一个简单的自定义组件,它从 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 的值,因此我从抛出的异常中看到了这一点:

Invalid Configuration – yii\base\InvalidConfigException

Hubspot API Key cannot be empty.

但是,如果我这样调用组件:

Yii::$app->hubspotDataManager

它确实传递了这个配置变量!为什么是这样?我必须做哪些额外的工作才能让组件加载它的应用程序配置数据以用于标准 class 实例化?我在文档中找不到有关此特定场景的任何信息。

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

不使用服务定位器创建实例时,配置当然是未知的。

流程是这样的,Yii::$app是一个Service Locator。它会将配置传递给依赖注入器容器 Yii::$container.

如果您想在不使用服务定位器的情况下传递配置 Yii::$app,您可以设置容器:

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

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

结果与使用服务定位器相同Yii::$app

您也可以像这样实例化 class 的新实例并将配置传递给它。

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