'How can I create a constructor in a Yii2 model

How can I create a constructor in a Yii2 model? because i want to convert a CI model to Yii2 model.

I would appreciate a working example.



Solution 1:[1]

Create this function in your model class:

function __construct()
{
    parent::__construct();
    ...
}

Solution 2:[2]

From the official documentation:

It is recommended that you perform object initialization in the init() method because at that stage, the object configuration is already applied. http://www.yiiframework.com/doc-2.0/yii-base-baseobject.html

So it depends a bit on what exactly you want to do in your constructor. For most cases, this would be the standard approach:

public function init()
{
    parent::init();

    // ... initialization after configuration is applied
}

Solution 3:[3]

The documentation tells us:

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.

So create a standard constructor in your model, but call parent::__construct() in the last line:

public function __construct($config = []) {
     // your init code here
     // ...
     parent::__construct($config);
}

// Controller

$model = new YourModel(['whatever' => []])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gmc
Solution 2 Patrick
Solution 3 Stijn de Witt