CAKEPHP 3正确修改控制器中请求数据的正确方法



上面有很多帖子,但似乎都过时了。

在2019年使用CakePHP 3.7,并在实施"密码重置"电子邮件的教程:http://web.archive.org/web/2017100115555555555555555555555555555555555555555555555555555555555555555555555555555555太平洋高-9-reset-password

该应用程序具有users表,该表具有2个称为passkeytimeout的字段。在上面链接的示例代码中,当用户重置其密码时,它们已使用以下来"删除"这两个字段:

$this->request->data['passkey'] = null;
$this->request->data['timeout'] = null;

看来这是不弃用的,您无法再在这样的控制器中设置请求数据。

我的计划是尝试使用array_merge()合并请求数据以及我们想这样修改的任何内容:

$save_data = array_merge($this->request->getData(), ['passkey' => null, 'timeout' => null]);
// Note $user is the result of a find query done earlier.
$this->Users->patchEntity($user, $save_data);

这样做似乎对保存在数据库中的数据没有影响 - 它将更新密码字段(来自链接帖子上的表单)。但是它不会修改DB中的passkeytimeout字段。

如果我debug($save_data)确实给我一个数组:

[
    'password' => 'foo',
    'confirm_password' => 'foo',
    'passkey' => null,
    'timeout' = null
];

这是错误的方法吗?我相信,这种变化的原因是与请求对象不变有关,尽管在编程上更容易通过$this->request设置数据。

我不是100%确定我已经了解了您的需求,但是可以通过将链接的代码重构为下面来确保重置函数中的PassKey和超时。这可能是一种方法...

//as

// Clear passkey and timeout
$this->request->data['passkey'] = null;
$this->request->data['timeout'] = null;
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
…

//到这个

$user = $this->Users->patchEntity($user, $this->request->getData());
// Clear passkey and timeout
$user->passkey = null;
$user->timeout = null;
if ($this->Users->save($user)) {
…

最新更新