1.使用方式
在rules中为每个字段配置验证器,在使用$model->validate()或$model->save()时,触发验证
$model->save()最终也是调用$model->validate()方法
2.$model->validate()方法解析
public function validate($attributeNames = null, $clearErrors = true)
{
...
$scenarios = $this->scenarios();
...
foreach ($this->getActiveValidators() as $validator) {
$validator->validateAttributes($this, $attributeNames);
}
...
}
public function scenarios()
{
...
$this->getValidators();
...
}
public function getActiveValidators($attribute = null)
{
$validators = [];
$scenario = $this->getScenario();
foreach ($this->getValidators() as $validator) {
if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->attributes, true))) {
$validators[] = $validator;
}
}
return $validators;
}
public function getValidators()
{
if ($this->_validators === null) {
$this->_validators = $this->createValidators();
}
return $this->_validators;
}
public function createValidators()
{
$validators = new ArrayObject;
foreach ($this->rules() as $rule) {
if ($rule instanceof Validator) {
$validators->append($rule);
} elseif (is_array($rule) && isset($rule[0], $rule[1])) {
$validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
$validators->append($validator);
} else {
throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
}
}
return $validators;
}
1).rules中的第2个参数是匿名函数或自定义的model中的一个方法
创建InlineValidator对象,此对象的method属性是匿名函数或model中自定义的验证方法
剩余的参数,键名作为对象的属性名,值作为此属性的值
2).rules中的第2个参数是yii框架validator内置的验证器
创建对应的内置验证器对象
剩余的参数,键名作为对象的属性名,值作为此属性的值
public static function createValidator($type, $model, $attributes, $params = [])
{
$params['attributes'] = $attributes;
if ($type instanceof \Closure || $model->hasMethod($type)) {
$params['class'] = __NAMESPACE__ . '\InlineValidator';
$params['method'] = $type;
} else {
if (isset(static::$builtInValidators[$type])) {
$type = static::$builtInValidators[$type];
}
if (is_array($type)) {
$params = array_merge($type, $params);
} else {
$params['class'] = $type;
}
}
return Yii::createObject($params);
}
个人博客链接:http://www.tanklh.cc/typecho/index.php/archives/6/