Kohana 的 ORM 带有内置的 Kohana 验证。
据我了解,它验证将添加到数据库中的字段。它对我不起作用,因为我需要验证来自$_POST
(简单来说)的字段。
让我给你举个例子。
在控制器中:
$data = Arr::extract($this->request->post(), array('username', 'password', 'password_repeatedly', 'email'));
try {
ORM::factory('User')->sign_up($data);
$this->request->redirect('sign-in');
} catch(ORM_Validation_Exception $exception) {
$errors = $exception->errors('error_messages');
echo 'There were errors:<br />';
echo Debug::dump($errors);
exit;
}
变量$data
是我需要验证的数组。方法sign_up()
只是我的 ORM 模型中将创建用户的自定义方法。对控制器中的“echo'es”和“exit's”感到抱歉 - 我只是在调试......
我的 ORM 模型如下所示:
public function rules() {
return array(
'username' => array(
array('not_empty')
),
'hashed_password' => array(
array('not_empty')
),
'email' => array(
array('not_empty')
)
);
}
public function sign_up($post) {
$salt = $this->_hurricane->generate_salt();
$hashed_password =
$this->_hurricane->hash_password($post['password'], $salt);
$this->username = $post['username'];
$this->hashed_password = $hashed_password;
$this->salt = $salt;
$this->email = $post['email'];
$this->save();
}
我想检查变量$data
的
这三个元素是否为空!正如我所说,它在ORM::save()
调用之前检查元素。如果你仔细看看我的代码......在我的自定义方法中,我已经设置hashed_password
好了。它会使它散列。问题是如果用户没有提交任何密码(我在我的 HTML 表单中将该字段称为“密码”,但在数据库中称为“hashed_password”)......如果没有提交密码 - 它将散列空字符串,这将导致散列反正。就这样hashed_password
定了!
然后验证被打开ORM::save()
并最终打开 - 密码永远不可能为空!如何处理?控制器中的额外验证?你会怎么处理?也许有点不同的逻辑?
PS 对我的代码的任何其他建议将不胜感激。谢谢指教!