模型规则的批量分配


Mass assignment of model rules

我想知道是否有一种简单的方法可以为模型批量分配一组新规则。

用例是,我可以有一个验证器规则,其中包含一组特定模型的子规则。我想动态加载该模型,分配其属性(我知道如何做到这两个),然后批量分配规则集。规则看起来像:

'rules' => array(
    array('road', 'string'),
    array('town', 'string'),
    array('county', 'string'),
    array('post_code', 'string'),
    array('telephone', 'integer')
)

我知道我可以通过单独挑选类并手动构建验证器来做到这一点,但有什么简单的方法可以告诉Yii模型用这个规范重新加载验证器吗?

我最终通过一个问题(https://github.com/yiisoft/yii/issues/987#issuecomment-8886072),其中提到查看CModel validatorList。在浏览了这段源代码一段时间后,我得到了以下代码,大部分是从CModel本身撕下来的:

$c=new EMongoModel();
foreach($this->rules as $rule){
    if(isset($rule[0],$rule[1]))  // attributes, validator name
        $c->validatorList->add->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
    else
        throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
                    array('{class}'=>get_class($this))));
}

现在,这使我可以获得一个数组元素列表,这些元素看起来像模型的验证规则,并当场将它们变成模型的验证规范。