开发者

Passing arguments and conditions to model in codeigniter

I'm adding some models to a project, and was wondering if there is a "best practice" kind of approach to creating models:

Does it make sense to create a function for each specific query?

I was starting to do this, then had the idea of creating a generic function that I could pass parameters to. e.g:

Instead of

function getClients开发者_运维问答(){
    return $this->db->query('SELECT client_id,last FROM Names ORDER BY id DESC');
    }
    function getClientNames($clid){
        return $this->db->query('SELECT * FROM Names WHERE client_id = '.$clid);
    }
    function getClientName($nameID){
        return $this->db->query('SELECT * FROM Names WHERE id ='.$nameID);
    }
}

Something like

function getNameData($args,$cond){
    if($cond==''){
        $q=$this->db->query('SELECT '.$args.' FROM Names');
        return $q;
    }else{
        $q=$this->db->query('SELECT '.$args.' FROM Names WHERE '.$cond);
        return $q;
    }
}

where I can pass the fields and conditions (if applicable) to the model. Is there a reason the latter example would be a bad idea?

Thanks!


I think it would actually be a better idea to use CI's Active Record to compile the queries.

An example:

function all_clients($select)
{
    $this->db->select($select);

    return $this->_get_client_data();
}

function single_client($select, $id = "")
{
    // validate $id

    $this->db->select($select);
    $this->db->where("id", $id);
    $this->db->limit(1);

    return $this->_get_client_data();
}

// Only called by a method above once the query parameters have been set.

private function _get_client_data()
{
    $q = $this->db->get("clients");

    if($q->num_rows() > 0)
    {
        return $q->result_array();
    }

    return FALSE;
}

CI's Active Record makes all the stuff you were wanting to much easier. You can imagine setting up your public functions to conditionally set a number of options before actually calling $this->db->get().

I guess you would call _get_client_data a catch-all (?) and running all your data retrieval through a single method makes stuff like error handling much easier to maintain.

NOTE: Always remember to validate data like this. I know you do, but I'm just repeating it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜