放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

Yii密码验证的实现过程

最近在看《应用Yii和PHP进行敏捷Web开发》的过程中,发现了一处有意思的地方。作者为了验证用户两次输入的密码是否一致,在class User中声明一个public $password_repeat;,然后在public function rules()中加了两句:

array('password', 'compare'),
array('password_repeat', 'safe'),

忽略表单的修改,只用这么几句就实现了password的验证,实在是令人惊奇:

作者解释道:幸运地是,Yii 的另外一个内部验证器 (CCompareValidator),可以完成你所期望的工作。他的工作是对比 2 个属性值,并且在不相等时返回一个错误消息。

看到这里我十分疑惑,没有一句代码告诉CCompareValidator,User类里面有一个$password_repeat是用来比较的,Yii框架是怎么知道有这个变量存在的呢?

后来我去查了查api文档http://www.yiiframework.com/doc/api/1.1/CCompareValidator#compareAttribute-detail 。关于CCompareValidator有这么一段解释:

The value being compared with can be another attribute value (specified via compareAttribute) or a constant (specified via compareValue. When both are specified, the latter takes precedence. If neither is specified, the attribute will be compared with another attribute whose name is by appending "_repeat" to the source attribute name.

当没有指定变量的时候,Yii将会默认查找XXX_repeat作为比较的对象。看来Yii里面都是这种约定俗成的小tricks呀

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » Yii密码验证的实现过程

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》