php - 处理 codeigniter 和 phpactiverecord 时出错

标签 php codeigniter error-handling phpactiverecord

我是 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/

相关文章:

mysql - 在Codeigniter中获取多个数组并插入数据库

mysql - 平均计算 codeigniter 查询

javascript - 错误处理 try & catch + 回调?

PHP json_encode 不适用于对象数组

javascript - undefined offset : 1 after exploding "/"

php - 从内存中执行suphp

r - if函数: the condition has length > 1 and only the first element will be used中的错误

php - 我的PHP中找不到的小错误。意外的T_VARIABLE

php - 更新表中的行值不起作用

php - 将输出发送到浏览器后设置 cookie