4

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.

sudip
  • 2,781
  • 1
  • 29
  • 41

3 Answers3

0

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.

Community
  • 1
  • 1
Bizley
  • 17,392
  • 5
  • 49
  • 59
  • 'prop1' => 3, 'prop2' => 7, [1, 2] ----- not working. Perhaps I dont need it anywhere or I can do it in other ways but question is why cant I do it or why there is no option to do it when it can be done by other 2 syntax ? – sudip Jul 04 '15 at 12:30
  • @sudip there is an option - you can always call new component object with "new *" or "Yii::createObject()" like you said. For me the app configuration is just to make it easier. Just to be sure, please try something like 'myComponent' => [['class' => ..., 'prop1' => ...], [1,2]] – Bizley Jul 04 '15 at 12:43
  • I tried that yesterday. It is throwing InvalidConfigException – sudip Jul 04 '15 at 13:23
0

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.

robsch
  • 9,358
  • 9
  • 63
  • 104