十月 CMS 模型 - 覆盖保存功能

October CMS Models - Overwrite save function

美好的一天,

我覆盖了我的十月 CMS 模型的保存功能。

 public function save(Array $options=[])

当我尝试保存时,出现错误。

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

所以我修改了保存功能

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

然后我得到这个令人困惑的错误。

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

那么,如果它在那里传递空值,考虑到 class 继承强制参数 1 成为数组,模型如何保存?

编辑:这是 /a/b/c/d/mysite/modules/backend/behaviors/FormController.php

的第 251 行
$modelToSave->save(null, $this->formWidget->getSessionKey());

所以基础 class 将接受空值,即使类型提示需要数组,但在覆盖函数后,不再接受空值?

您的方法签名与原始 October\Rain\Database\Model 方法签名不匹配。如果您阅读原文 source,您会看到 $options 的默认值是 null

这很重要,因为它告诉 PHP 参数值应该是 arraynull。目前,您的函数只需要 array

public function save(array $options = null, $sessionKey = null)
{
    // ...
}

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

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