Cakephp 4.0 中的validationDefault 声明

Sha*_*ron 1 cakephp

我正在尝试使用 CakePHP 4.0 创建一个站点,但无法使验证规则起作用。我阅读了文档,但不确定应该将 validationDefault 函数放在哪里。我把它放在 UsersTable.php 中,它看起来像这样:

<?php

namespace App\Model\Table;

use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class UsersTable extends Table {

    public function initialize(array $config): void {

        $this->addBehavior('Timestamp');

        $this->hasMany('Requests')
                ->setDependent(true);

        $this->hasMany('Offers')
                ->setDependent(true);

    }

    public function validationDefault(Validator $validator) {

        $validator->notEmptyString('email', 'Please enter your email address')
                  ->notEmptyString('name', 'Please enter a name');

        return $validator;
    }
}

?>
Run Code Online (Sandbox Code Playgroud)

所以我希望如果用户尝试在没有电子邮件或姓名的情况下登录,它应该会抛出一个错误。

我的注册表格是:

        echo $this->Form->create();
        echo $this->Form->control('name');
        echo $this->Form->control('email');
        echo $this->Form->control('password', array('type' => 'password'));
        echo $this->Form->control('confirm_password', array('type' => 'password'));
        echo $this->Form->button('Register');
        echo $this->Form->end();
Run Code Online (Sandbox Code Playgroud)

并将数据发送到 UsersController.php,其中包含:

public function login() {

                // Otherwise, we're registering
                $users = TableRegistry::getTableLocator()->get('Users');
                $user = $users->newEntity($this->request->getData());
                if ($users->save($user)) {
                    $result = $this->Authentication->getResult();
                    if ($result->isValid()) {
                        $target = '/users/home';
                        return $this->redirect($target);
                    }
                }else {
                    $this->Flash->error('Please fix errors below');
                }
                exit;
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

当我尝试在不输入姓名和电子邮件的情况下注册时,收到以下错误消息:

Fatal error: Declaration of App\Model\Table\UsersTable::validationDefault(Cake\Validation\Validator $validator) must be compatible with Cake\ORM\Table::validationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator in /Applications/MAMP/htdocs/src/Model/Table/UsersTable.php on line 26
Run Code Online (Sandbox Code Playgroud)

我的代码看不到任何明显的问题。我哪里错了?

Gre*_*idt 6

validationDefaultCake中函数的声明是:

public function validationDefault(Validator $validator): Validator
Run Code Online (Sandbox Code Playgroud)

你的声明只是

public function validationDefault(Validator $validator)
Run Code Online (Sandbox Code Playgroud)

您需要在末尾添加返回类型声明才能匹配。文档似乎没有提到这一点,您可能想就此提出问题。