How to override model's constructor correctly

2020-03-04 07:50发布

I have troubles with testing Model in CakePHP 2.0 and it seems the problem is on the model's constructor.

public function __construct(){
    parent::__construct(); 
    $this->_pagi_cuantos = 2;
}

Even if I delete all its content, I still getting problems trying to run the test.

Mark Story told me:

if you have a constructor make sure you're overriding the constructor correctly. Failing to do so will cause errors like this.

What do I wrong?

3条回答
地球回转人心会变
2楼-- · 2020-03-04 08:08

why don't you look into the core code its open source after all: https://github.com/cakephp/cakephp/blob/2.1/lib/Cake/Model/Model.php#L653

so for all your models:

public function __construct($id = false, $table = null, $ds = null) {
    parent::__construct($id, $table, $ds);
}
查看更多
手持菜刀,她持情操
3楼-- · 2020-03-04 08:17

One way that I found is to do something like this:

function __construct() {
    call_user_func_array(array('parent', '__construct'), func_get_args());
}

It allows you to not have to worry about what the parent gets passed. Although that code is pretty hideous.

查看更多
够拽才男人
4楼-- · 2020-03-04 08:22

Rather than override the constructor, how about using beforeFilter() for controllers or the before methods for the Model such as beforeFind(), beforeValidate(), etc.

查看更多
登录 后发表回答