October CMS Models - Overwrite save function

时间:2017-12-18 07:27:30

标签: php oop octobercms

Good day,

I overwrote the save function of my October CMS model.

 public function save(Array $options=[])

When I tried to save, it threw an error.

Declaration of MyCompany\MyPlugin\Models\MyModel::save(array $options = Array) should be compatible with October\Rain\Database\Model::save(array $options = NULL, $sessionKey = NULL)" on line 42 of /a/b/c/d/mysite/plugins/mycompany/myplugin/models/MyModel.php

So I modified the save function.

public function save(Array $options=[], $sessionKey=null)

Then I get this confusing error.

Type error: Argument 1 passed to MyCompany\MyPlugin\Models\MyModel::save() must be of the type array, null given, called in /a/b/c/d/mysite/modules/backend/behaviors/FormController.php on line 251" on line 38 of /a/b/c/d/mysite/plugins/mycompany/myplugin/models/MyModel.php

So, if it's passing a null there, how are models saving, considering the class inheritance forces argument 1 to be an array?

Edit: Here is line 251 of /a/b/c/d/mysite/modules/backend/behaviors/FormController.php

$modelToSave->save(null, $this->formWidget->getSessionKey());

So the base class will accept nulls, even if type hinting requires Array, but upon overwriting the function, nulls are no longer accepted?

2 个答案:

答案 0 :(得分:2)

我认为最好的选择是使用模型事件https://octobercms.com/docs/database/model#events

public function beforeSave()
{
    $this->slug = Str::slug($this->name);
}

答案 1 :(得分:1)

Your method signature does not match the original [] method signature. If you read the original source, you'll see that the default value for October\Rain\Database\Model is $options.

This is important, because it tells PHP the parameter value should be either an null or array. Presently, your function requires an null only.

array