• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
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){
        $q=$this->db->query('SELECT '.$args.' FROM Names');
        return $q;
        $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?


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!

Excellent. Thanks very much for the reply!

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.

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

    return $q->row();

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.