我有一个我想用作组件的库。在配置文件中我这样设置:
'components' => [
'superLib' => [
'class' => 'SuperLib'
// '__construct' => [$first, $second] Maybe Yii 2 have property for this
],
],
如何将数据传递给 __construct()
?
最佳答案
大多数时候您不必重写 __construct()
。
几乎 Yii 2 中的每个对象都是从 yii\base\Object 扩展而来的它通过配置数组功能具有赋值属性。
组件是从 yii\base\Component 扩展而来的,后者也是从 yii\base\Object
扩展而来的。因此,在您的示例中连同类名(请注意,您应该提供带有命名空间的完整类名,而在您的示例中它位于根命名空间中)您可以传递任何属性/值对:
'components' => [
'superLib' => [
'class' => 'SuperLib'
'firstProperty' => 'firstPropertyValue',
'secondProperty' => 'secondPropertyValue',
],
],
有时你需要使用init()方法(例如检查值是否具有有效类型并抛出某种异常,设置默认值等):
public function init()
{
parent::init(); // Call parent implementation;
...
}
以下是来自官方文档的一些有用信息:
Besides the property feature, Object also introduces an important object initialization life cycle. In particular, creating an new instance of Object or its derived class will involve the following life cycles sequentially:
- the class constructor is invoked;
- object properties are initialized according to the given configuration;
- the
init()
method is invoked.In the above, both Step 2 and 3 occur at the end of the class constructor. It is recommended that you perform object initialization in the
init()
method because at that stage, the object configuration is already applied.In order to ensure the above life cycles, if a child class of Object needs to override the constructor, it should be done like the following:
public function __construct($param1, $param2, ..., $config = [])
{
...
parent::__construct($config);
}
That is, a
$config
parameter (defaults to[]
) should be declared as the last parameter of the constructor, and the parent implementation should be called at the end of the constructor.
如果仍然想在 __construct
中使用额外的参数,你可以这样做:
'components' => [
'superLib' => [
'class' => 'app\components\SuperLib',
['firstParamValue', 'secondParamValue'],
],
],
可以在官方文档中找到here在第三个例子中。
关于php - Yii2 组件将数据传递给 __construct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129614/