CakePHP 3-组合可重用的验证器以用于表中的重复列吗?

时间:2019-07-09 11:20:19

标签: validation cakephp cakephp-3.0 cakephp-3.x

目标:我有一个数据库,其中包含许多共享许多列的表。例如,users表和orders表都有一组四个组成地址的列。与其在每个表的validationDefault()函数中重复相同的规则,不如让这些规则可重用。

附件:我查看了Book: Creating Reusable Validatorsstackoverflow question on the topic,并了解了这种用法:

public function validationCustomAndDefault()
{
    $validator = new \App\Model\Validation\CustomModelValidator();

    return $this->validationDefault($validator);
}

问题:基于验证功能,自定义验证会创建一个新的验证对象。我想结合多个可重复使用的验证。我怎么能意识到这一点?因此,在某种伪代码中:

// In src/Model/Table/UsersTable

public function validationDefault(Validator $validator)
{
    $validator1 = new \App\Model\Validation\CustomAddressValidator(); // Bunch of columns defined in there
    $validator2 = new \App\Model\Validation\CustomOtherValidator();

    $validator = validator1 + $validator2;

    return $validator;
}

1 个答案:

答案 0 :(得分:0)

我最终使用了静态函数。定制验证器类:

<?php

namespace App\Model\Validation;

use Cake\Validation\Validator;

/**
 * Validation for the four address fields
 */
class AddressValidator extends Validator
{

    static public function addAddressFields(&$validator)
    {
        // Add validation rules to existing validator

        $validator
                ->scalar('address_city')
        // ...
    }
}

我的UsersTable.php中的用法:

class UsersTable extends Table
{
    // ...

    public function validationDefault(Validator $validator)
    {
        $validator
            ->nonNegativeInteger('id')
            ->allowEmptyString('id', 'create');

        // ...

        AddressValidator::addAddressFields($validator);
    }
}