Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 component pass data to __construct

Tags:

php

yii

yii2

I have a lib which I want to use as component. In config file I set it like that:

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

How I can pass data to __construct()?

like image 276
Jack Avatar asked Mar 17 '23 17:03

Jack


1 Answers

Most of the times you don't have to override __construct().

Pretty much every object in Yii 2 is extended from yii\base\Object which has assignment properties through configurational array feature.

Components is extended from yii\base\Component, the latter is extended from yii\base\Object too. So in your example along with class name (note that you should provide full class name with namespace while in your example it's in the root namespace) you can pass any properties / values pairs:

'components' => [
    'superLib' => [
        'class' => 'SuperLib'
        'firstProperty' => 'firstPropertyValue',
        'secondProperty' => 'secondPropertyValue',
    ],
],

Sometimes you need to use init() method (for example for checking if values have valid types and throw some kind of exceptions, for setting default values, etc.):

public function init()
{
    parent::init(); // Call parent implementation;

    ...
}

Here is some useful info from official docs:

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.

If nevertheless want to use additional parameters in __construct you can do it like that:

'components' => [
    'superLib' => [
        'class' => 'app\components\SuperLib',
        ['firstParamValue', 'secondParamValue'],
    ],
],

You can find it in official docs here in third example.

like image 174
arogachev Avatar answered Mar 24 '23 02:03

arogachev