我喜欢在Redbean
PHP中使用FUSE模型进行验证的想法.
我的应用程序有时需要通过多个源(表单,文件等)接受数据,因此将验证放在实际的类更新上是有意义的.
查看Redbean站点上的示例,验证似乎基于抛出异常.
当然,你只能抛出一个异常,所以我假设我需要在我的FUSE类中创建一个类型为“array”的附加属性来保存与各个字段相关的验证消息.
有没有人有更好的想法?这是我到目前为止一直在尝试的…
your name:
your email:
your message:
/**
* @property $name string
* @property $email string
* @property $message string
*/
class Model_Comment extends RedBean_SimpleModel{
public $invalid = array();
public function update(){
if(empty($this->name)) $this->invalid['name'] = "field is empty";
if(empty($this->email)) $this->invalid['email'] = "field is empty";
if(empty($this->message)) $this->invalid['message'] = "field is empty";
if(count($this->invalid) > 0) throw new Exception('Validation Failed!');
}
public function getInvalid(){
return $this->invalid;
}
}
if(isset($_POST['send'])){
$comment = R::dispense('comment');
/* @var $comment Model_Comment */
$comment->import($_POST,'name,email,message');
try{
R::store($comment);
}
catch(Exception $e){
echo $e->getMessage();
$invalid = $comment->getInvalid();
print_r($invalid);
exit;
}
echo '
thank you for leaving a message.
';}
echo "
What people said!
";$comments = R::find('comment');
/* @var $comments Model_Comment[] */
foreach($comments as $comment){
echo "
{$comment->name}: {$comment->message}
";}
?>