Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 233
Donny Akhmad Septa Utama Avatar asked Dec 12 '25 04:12

Donny Akhmad Septa Utama


2 Answers

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
}
like image 121
Patrick Avatar answered Dec 14 '25 01:12

Patrick


Create this function in your model class:

function __construct()
{
    parent::__construct();
    ...
}
like image 30
gmc Avatar answered Dec 14 '25 00:12

gmc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!