开发者

OOP MVC - model or controller to check return data type?

Sometimes i need data like array and sometime开发者_如何学Cs i need same data as json.

Where would you do the check if is a ajax call, in controller or model or... Which one is better?

Test if is ajax call in controller

function my_controller(){
    //getdata from model
    $data=$this->my_model();
    if(THIS_IS_AJAX_CALL){
        echo json_encode($data);
    }else{
        return $data;
    }
}

function my_model(){
    //get the data from db
    return $data;
}

Pass type as argument to model:

function my_controller(){
    if(THIS_IS_AJAX_CALL){
        return $this->my_model('json');
    }else{
        return $this->my_model();
    }
}

function my_model($type=''){
    //get the data from db
    if($type='json'){
        return json_encode($data);
    }else{
        return $data;
    }
}


The controller. The model does not care how the data needs to be represented to the user, only the data itself.


A quote from the Codeigniter tutorial explaining MVC:

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.

  • The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".

  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

I think you should check in the controller(this has nothing to do with datastructures) the header to see if it is an ajax call, because jquery sets headers. If it is an Ajax call you should do the desired json_encode transformattion. I think your code should look something along the lines of the code below:

function is_xhr() {
  return @ $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] === 'XMLHttpRequest';
}

$data = /* get from model */
if( is_xhr() ){
  // Not explicitly needed, but we like being accurate, right?:
  header('Content-type: application/json');

  echo json_encode($data);
  exit(); // We don't need to render anything else
} else {
  echo $data;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜