为什么Yii2使用数组而不是对象?

时间:2017-02-07 13:09:47

标签: validation yii2 models rules

Yii2模型中的规则如下所示:

[
    // checks if "level" is 1, 2 or 3
    ['level', 'in', 'range' => [1, 2, 3]],
]

如果他们是这样的对象会不会更好?

[
  new RangeRule('level', [1, 2, 3])
]

1 个答案:

答案 0 :(得分:1)

您可以使用如下验证器对象:

use yii\validators\Validator;
use yii\validators\NumberValidator;
use yii\validators\StringValidator;

class TestModel extends \yii\base\Model
{
    public $firstProperty;
    public $secondProperty;

    public function rules()
    {
        return [
            new NumberValidator(['attributes' => ['firstProperty'], 'integerOnly' => true, 'min' => 0, 'max' => 100]),
            new StringValidator(['attributes' => ['secondProperty'], 'max' => 5]),
        ];
    }
}

此外,您可以根据需要装饰这些对象(使用其他类和方法):

class TestModel extends \yii\base\Model
{
    public $firstProperty;
    public $secondProperty;

    public function rules()
    {
        // Prepare Int validator
        $validatorInt              = new NumberValidator();
        $validatorInt->integerOnly = true;
        $validatorInt->min         = 0;
        $validatorInt->max         = 100;

        // Prepare String validator
        $validatorString      = new StringValidator();
        $validatorString->max = 5;

        // Make rules
        return [
            static::_makeRule(['firstProperty'], $validatorInt),
            static::_makeRule(['secondProperty'], $validatorString),
        ];
    }

    protected function _makeRule($attrName, Validator $validatorObj)
    {
        $validatorObj = clone $validatorObj;

        $validatorObj->attributes = (array)$attrName;

        $validatorObj->init();                          // Initializes validator and normalizes values

        return $validatorObj;
    }

}