开发者

Error handling codeigniter and phpactiverecord

开发者 https://www.devze.com 2023-04-03 19:13 出处:网络
I\'m new to CodeIgniter and PhpActiverecord and I\'m wondering how to best propagate errors from the Model to the Controller when using CI and phpactiverecord. As a simple example consider this:

I'm new to CodeIgniter and PhpActiverecord and I'm wondering how to best propagate errors from the Model to the Controller when using CI and phpactiverecord. As a simple example consider this:

class Book extends ActiveRecord\Model {

  static $validates_presence_of = array(
    array('title')
  );

  public static function new_book($title){
    $new_record = Book::cre开发者_如何转开发ate(array(
      'title' => $title
    ));

    if($new_record->is_invalid())
      //propagate error with $new_record->errors->full_messages()
    else
      return $new_record;
  }

}

Should I have a variable in my controller that checks if errors has been set or should I just return $new_record whatever happens and do the is_invalid() check in the controller? I would like to do most of the work in the model (to follow the "fat model skinny controller" principle) but I can't really see a "nice" way of propagating the errors to the controller and on to the view.


Why not add an error reporting method to the model

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;
  }

}

In the controller, test if a false or NULL value is returned. If so you can call the get_errors() method, do any additional formatting if you choose to, and pass the array to the view.

0

精彩评论

暂无评论...
验证码 换一张
取 消