Welcome Guest, Not a member yet? Register   Sign In
Passing arguments and conditions to model in codeigniter
#1

[eluser]dionysus[/eluser]
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
Code:
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

Code:
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!
#2

[eluser]erik.brannstrom[/eluser]
There are really no right or wrongs here! All you can do is think about what is the easiest to use and go with it!

Personally though, I would prefer some form of the latter since that provides a higher level of abstraction. It's good to let your methods do some heavy lifting, it's one of the things they are there for!
#3

[eluser]dionysus[/eluser]
Excellent. Thanks very much for the reply!
#4

[eluser]Aken[/eluser]
For me, it would depend on how many of those arguments you end up using. Will your SELECT arguments vary that much throughout your application?

For me, models are designed to alleviate the many different variations you have of writing DB queries. They're meant to simplify the retrieval of data. I shouldn't have to add lots of parameters to my models, because then I'm just writing the queries individually again.

That said, if I found myself needing to add odd, specific arguments or conditions often, I probably would create a catch-all type model function like that. But only if the need arose. I'd prefer to keep my models specific.

Code:
// Specific function.
function getName($id)
{
    $q = $this->db->get_where('Names', array('name_id' => $id));

    return $q->row();
}




Theme © iAndrew 2016 - Forum software by © MyBB