sudip
sudip

Reputation: 2850

Yii 2 custom component in application configuration file

I have declared a class

class MyClass extends Component {

    public $prop1;
    public $prop2;

    public function __construct($param1, $param2, $config = [])
    {
        // ... initialization before configuration is applied

        parent::__construct($config);
    }
..............

Now, I can create instance of it by using

$component1 = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]);

OR,

$component2 = \Yii::createObject([
            'class' => MyClass::className(),
            'prop1' => 13,
            'prop2' => 40,
        ], [1, 2]);

Now, I want to register it as a application component. I can do that by doing following :

'components' => [
        'myComponent' => [
            'class' => 'frontend\components\MyComponent',
            'prop1'=>3,
            'prop2'=>7
        ],

But, when I register it as a application component, how can I pass values for $param1 and $param2 in the constructor ?

Thanks.

Upvotes: 4

Views: 5936

Answers (3)

robsch
robsch

Reputation: 9718

Found this information in the guide: In order to set constructor parameters in the component declarations of the application configuration you have to use __construct() as key in the configuration and provide an array as value. I.e.:

'components' => [
    'myComponent' => [
        'class' => 'frontend\components\MyComponent',
        '__construct()' => [1, 2],
        'prop1' => 3,
        'prop2' => 7,            
    ],

This was added with version 2.0.29.

Upvotes: 0

Bizley
Bizley

Reputation: 18021

This answer suggests doing it like so:

'components' => [
    'myComponent' => [
        'class' => 'frontend\components\MyComponent',
        'prop1' => 3,
        'prop2' => 7,
        [1, 2]
    ],

but I haven't tried it.

The question is why you want to make it as configurable component with constructor parameters?

If the constructor parameters in the component are meant to be given in config (so rather unchanged later on) it might be better to prepare extended class from MyComponent where the constructor params are already set.

The second approach is to prepare $param1 and $param2 to be component parameters (so something like prop3 and prop4) so you can modify it in easy way and you don't have to override constructor.

Upvotes: 0

Related Questions