chr*_*ian 5 php validation exception-handling redbean
我喜欢在RedbeanPHP中使用FUSE模型进行验证的想法.
我的应用程序有时需要通过多个源(表单,文件等)接受数据,因此将验证放在实际的类更新上是有意义的.
查看Redbean站点上的示例,验证似乎基于抛出异常.
当然,你只能抛出一个异常,所以我假设我需要在我的FUSE类中创建一个类型为"array"的附加属性来保存与各个字段相关的验证消息.
有没有人有更好的想法?这是我到目前为止一直在尝试的...
<form action="" method="post">
<p>your name: <input name="name" type="text"></p>
<p>your email: <input name="email" type="text"></p>
<p>your message:</p>
<textarea name="message" id="" cols="30" rows="10"></textarea>
<input name="send" value="send message" type="submit">
</form>
<?php
/**
* @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 '<p>thank you for leaving a message.</p>';
}
echo "<h2>What people said!</h2>";
$comments = R::find('comment');
/* @var $comments Model_Comment[] */
foreach($comments as $comment){
echo "<p>{$comment->name}: {$comment->message}</p>";
}
?>
Run Code Online (Sandbox Code Playgroud)
mav*_*mav 10
您可以扩展RedBean_SimpleModel类以向其添加自己的方法和字段,因此它将适用于您的所有模型.然后,您可以使用事务来管理验证.它可能看起来像这样(代码未测试):
class RedBean_MyCustomModel extends RedBean_SimpleModel {
private $errors = array();
public function error($field, $text) {
$this->errors[$field] = $text;
}
public function getErrors() {
return $this->errors;
}
public function update() {
$this->errors = array(); // reset the errors array
R::begin(); // begin transaction before the update
}
public function after_update() {
if (count($this->errors) > 0) {
R::rollback();
throw new Exception('Validation failed');
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您的模型可能如下所示:
class Model_Comment extends RedBean_MyCustomModel {
public function update(){
parent::update();
if(empty($this->name)) $this->error('name', 'field is empty');
if(empty($this->email)) $this->error('name', 'field is empty');
if(empty($this->message)) $this->error('name', 'field is empty');
}
public function getInvalid(){
return $this->invalid;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2380 次 |
| 最近记录: |