【发布时间】:2016-02-24 08:58:24
【问题描述】:
我正在学习 Yii2。这是我没有用谷歌搜索答案的一种情况。
我在config/console.php的$config['components']数组中注册了一个名为scraper的组件,
这个scraper 类有一个公共属性$_client,它是一个Goutte\Client 类。
我尝试使用下面的方式设置scraper组件,但是不行,Yii2没有将$_client实例化为Goutte\Client对象。
$config = [
'scraper' => [
'class' => 'app\models\Scraper',
'_pageSize' => 10,
'_client' => [ //not working. can not instantiate this property as an object
'class' => 'Goutte\Client'
],
],
//...
]
问题:在配置中注入依赖的工作方式是什么?
【问题讨论】:
-
Scraper 是从 Model 派生的吗?
_client是公共成员吗? Goutte\Client 是完全限定的类名(不是 app\goutte\Client)?而Goutte\Client构造函数没有参数? -
Scraper 派生自
Component,$_client是公共成员。当我在Scraper类的 init() 函数中初始化 $_client 时,而所有其他公共原始类型属性都在此配置文件中设置,它工作正常。如果我在 Scraper 函数中var_dump($this->_client),它显示$this-_client是 array(1) { ["class"]=> string(13) "Goutte\Client" } 的数组。 -
Goutte\Client是完整的类名,不需要参数。我可以在 Scraper 类中通过use Goutte\Client导入这个类。 -
能否提供更多代码(类、命名空间、命名空间用法、配置...),好吗?在 $config 中,我看不到
components键。我对配置不是很有经验,所以不确定我是否可以帮助你。 -
@robsch,是的,我跳过了这段代码 sn-p 的
components部分,原因是,除了这个$_client属性之外,其他所有属性都被实例化了,所以我只想突出这部分。并感谢您尝试帮助我:)
标签: dependency-injection configuration yii2 config