【问题标题】:Yii2 Component class not loading config when instantiatedYii2组件类在实例化时不加载配置
【发布时间】:2018-05-10 13:39:53
【问题描述】:

我创建了一个从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 使用基本应用程序模板。

【问题讨论】:

    标签: php configuration yii2 yii2-basic-app


    【解决方案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 相同。

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 2021-12-18
    • 2016-12-01
    • 2011-04-27
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多