当模型在MVC中找不到DB中的记录时,在哪里传递回消息


Where to pass back message when Model cannot find a record in DB in MVC?

我想知道从模型到控制器传递成功或失败消息的最佳消息是什么?成功消息很简单,因为我们可以传回数据。然而,对于失败,我们只能传递FALSE,而不能传递失败的回调结果。

最好的方法是什么?

方法一:

模型如下:

function get_pkg_length_by_id($data) {
    $this->db->where('id', $data['pkg_length_id']);
    $result = $this->db->get('pkg_lengths');
    if($result->num_rows() > 0 ) {
        return $result->row();
    }
    else {
        return false;
    }
}
在控制器中,我将执行
function show() {
    if(get_pkg_length_by_id($data) { 
        //pass success message to view
    }
    else {
        //Pass failure message to view
    }

版本2:

模型中

function get_pkg_length_by_id($data) {
    $this->db->where('id', $data['pkg_length_id']);
    $result = $this->db->get('pkg_lengths');
    if($result->num_rows() > 0 ) {
        $result['status'] = array(
            'status' => '1',
            'status_msg' => 'Record found'
        );
        return $result->row();
    }
    else {
        $result['status'] = array(
            'status' => '0',
            'status_msg' => 'cannot find any record.'
        );
        return $result->row();
    }
}
在控制器

function show() {
$result = get_pkg_length_by_id($data);
    if($result['status['status']] == 1) { 
        //pass $result['status'['status_msg']] to view
    }
    else {
        //pass $result['status'['status_msg']] to view
    }

我不能肯定地说哪个是最好的。我可以说我经常使用选择# 2,我从服务器传递错误,通常以特定的形式这样做,我的控制器的任何子类都可以解析并发送给视图。

同样,在show()函数中,else是无关的,一旦返回,将跳出该函数,因此可以这样做:

if($result->num_rows() > 0 ) {
    $result['status'] = array(
        'status' => '1',
        'status_msg' => 'Record found'
    );
   //the condition is met, this will break out of the function
    return $result->row();
}
$result['status'] = array(
  'status' => '0',
   'status_msg' => 'cannot find any record.'
);
return $result->row();

在模型页中做这些事情总是一个好的做法。

我对你所做的做了一些修改,如下:

function get_pkg_length_by_id($data) 
{
    $this->db->where('id', $data['pkg_length_id']);
    $query = $this->db->get('pkg_lengths');
    /*
        Just changed var name from $result to $query
        since we have a $result var name as return var
    */
    if($result->num_rows() > 0 ) {
        $result = $query->row_array();
        /*
            $result holds the result array.
        */
        $result['status'] = array(
            'status' => '1',
            'status_msg' => 'Record found'
        );
        //return $result->row();
        /*
          This will return $result->row() only which 
          doesn't include your $result['status']
        */
    }
    else {
        $result['status'] = array(
            'status' => '0',
            'status_msg' => 'cannot find any record.'
        );
        //return $result->row();
        /*
        This is not required.
        Returning just status message is enough.
        */
    }
    return $result;
}