akshaypjoshi
akshaypjoshi

Reputation: 1295

Which is better way to initialise Component in Yii2?

I have created one component in Yii2 and extends it with yii\base\Component.

Now, I want to initialise the component that I have created which can be done in two ways

  1. Using new:

    $sampleClass = new SampleClass();
    
  2. Putting Component in config file:

    'sampleClass' => [
        'class' => 'app\components\SampleClass',
    ], 
    

    and accessing it like Yii::$app->sampleClass.

What is difference between them and which is better way to initialise component?

Upvotes: 1

Views: 296

Answers (1)

rob006
rob006

Reputation: 22174

It mostly depends on your needs. Defining component in config and using it as Yii::$app->sampleClass creates one instance which can be easily configured at config level and shared across project. The perfect examples are DB connection or URL manager - usually you want to use the same instance of these components in multiple places, and you want to be able to easily configure them. Defining them in config and using as Yii::$app->component is natural choice in Yii (although it is bad practice overall and using Yii::$app as static service locator may be problematic in big applications).

Using new keyword or Yii::createObject() is better option if you don't want to share component or you want to pass it as dependency directly.

Upvotes: 1

Related Questions