我是 CodeIgniter 和 PhpActiverecord 的新手,我想知道在使用 CI 和 phpactiverecord 时如何最好地将错误从模型传播到 Controller 。作为一个简单的例子考虑这个:
class Book extends ActiveRecord\Model {
static $validates_presence_of = array(
array('title')
);
public static function new_book($title){
$new_record = Book::create(array(
'title' => $title
));
if($new_record->is_invalid())
//propagate error with $new_record->errors->full_messages()
else
return $new_record;
}
}
我是否应该在我的 Controller 中有一个变量来检查是否已设置错误,或者我应该只返回 $new_record
无论发生什么,然后执行 is_invalid()
检查 Controller ?我想在模型中完成大部分工作(遵循“胖模型瘦 Controller ”原则)但我真的看不到将错误传播到 Controller 和 View 的“好”方式。
最佳答案
为什么不在模型中添加报错方法
class Book extends ActiveRecord\Model {
private $errors = array();
public function get_errors() {
return $this->errors;
}
static $validates_presence_of = array(
array('title')
);
public static function new_book($title){
$new_record = Book::create(array(
'title' => $title
));
if($new_record->is_invalid())
//propagate error with $new_record->errors->full_messages()
$this->errors[] = $new_record->errors->full_messages()
else
return $new_record;
}
}
在 Controller 中,测试是否返回了 false 或 NULL 值。如果是这样,您可以调用 get_errors() 方法,根据需要进行任何其他格式设置,然后将数组传递给 View 。
关于php - 处理 codeigniter 和 phpactiverecord 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352408/