【发布时间】: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