Yii2 组件将数据传递给 __construct

Yii2 component pass data to __construct

我有一个我想用作组件的库。在配置文件中我这样设置:

'components' => [
    'superLib' => [
        'class' => 'SuperLib'
         // '__construct' => [$first, $second] Maybe Yii 2 have property for this 
    ],
],

如何将数据传递给 __construct()

大多数情况下您不必重写 __construct()

几乎 Yii 2 中的每个对象都是从 yii\base\Object 扩展的,它通过配置数组功能具有赋值属性。

Components 是从 yii\base\Component 扩展而来,后者也是从 yii\base\Object 扩展而来。因此,在您的示例中连同 class 名称(请注意,您应该提供带有名称空间的完整 class 名称,而在您的示例中它位于根名称空间中)您可以传递任何属性/值对:

'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 第三个例子