Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: How can I create constructor in a controller?

Tags:

yii2

How can I create a constructor in a Yii2 controller? I am trying to find out what exactly is the $id $module and $config = [] in the parent::__construct arguments.

public function __construct($id, $module, $config = [])
{
    $this->id = $id;
    $this->module = $module;
    parent::__construct($config);
}

I would appreciate a working example.

like image 879
Zack Avatar asked Oct 18 '25 14:10

Zack


1 Answers

There shouldn't be anything wrong with

public function __construct($id, $module, $config = [])
{
    \yii\helpers\VarDumper::dump([$id, $module, $config]);
    parent::__construct($id, $module, $config);
}

if the goal is to investigate what happens there.

For production it is better to stick to overriding init method and use $this->id and $this->module there if needed. That's where the framework expects initialization code to be placed:

It is recommended that you perform object initialization in the init() method because at that stage, the object configuration is already applied.

like image 168
Estus Flask Avatar answered Oct 22 '25 00:10

Estus Flask