CakePHP 3 验证 validateUnique 错误

CakePHP 3 validation validateUnique error

我已经创建了一个验证器,我试图让它检查一个字段是否是唯一的,我想我的规则没问题,但它抛出了一个致命错误:

Fatal error: Using $this when not in object context in route/app/vendor/cakephp/cakephp/src/ORM/Table.php on line 2113

严格的标准也告诉我:

Non-static method Cake\ORM\Table::validateUnique() should not be called statically [CORE/src/Validation/ValidationRule.php, line 140]

这是 Cake 3 中的错误吗?我只使用核心方法...

我的蛋糕版本是3.0.1

验证者代码:

<?php namespace App\Model\Validation;

use Cake\Validation\Validator;

class SiteValidator extends Validator
{
    public function __construct()
    {
        parent::__construct();
        $this->provider('table', 'Cake\ORM\Table');

        $this
        ->add('id', 'valid', ['rule' => 'numeric'])
        ->allowEmpty('id', 'create')
        ->requirePresence('subdomain', 'create')
        ->notEmpty('subdomain')
        ->add('subdomain', 'validFormat', [
              'rule' => 'alphanumeric',
              'message' => 'El subdominio solo puede contener números y letras sin tildes.',
              ])
        ->add('subdomain', [
              'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
              ])
        ->requirePresence('name', 'create')
        ->notEmpty('name')
        ->add('profile_count', 'valid', ['rule' => 'numeric'])
        ->requirePresence('profile_count', 'create')
        ->notEmpty('profile_count');
    }
}

来电:

use App\Model\Validation\SiteValidator;

....
$validator = new SiteValidator();
$validator->errors( $this->request->data )

您将 table 提供程序定义为 class 名称,因此这是预期的行为,验证器将在这种情况下静态调用 validateUnique()

Cookbook > Validation > Adding Validation Providers

您必须传递一个实际的 table class 实例才能使用 tables 验证方法:

$sitesTable = TableRegistry::get('Sites');
$validator->provider('table', $sitesTable);

或者,这可能是更好的选择,在您的 table class 上定义一个验证器,并将 validate 选项与 newEntity()/newEntities() 一起使用/patchEntity()/patchEntities().

$sitesTable->validator('site', $validator);
$entity = $sitesTable->newEntity($this->request->data, [
    'validate' => 'site'
]);

另见