views:

46

answers:

3

In my codeigniter project I have

<?php
class User_model extends Model {
    function user_model()
    {
        parent::Model();
    }

    // should we use instance method?
    function get_total_users_count(){
     $results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");
     if($results){
      return $results->num_rows();
     }
     return 0;
    }

    // or class method?
    public static function get_total_users_count(){
     $obj =& get_instance();
     $results = $obj->db->query("SELECT * FROM bhr_users GROUP BY userid");
     if($results){
      return $results->num_rows();
     }
     return 0;
    }
}
?>

I feel like this should be a class level method because it operates on multiple users. Do you agree? Is get_instance the proper way to do this in codeigniter?

A: 

You should be using

$results = $this->db->query("SELECT * FROM bhr_users GROUP BY userid");

Unless you are getting an instance of another class, you should do it this way.

Thorpe Obazee
Your suggestion would require making the method non-static.
Mike B
+1  A: 

Honestly, I don't think there's one right way for this. I'd say the instance method is the most common way, but that's not to say that it's right or wrong.

One big difference between CodeIgniter and some other frameworks is that models can be whatever you want them to be. According to the CI manual "The Model represents your data structures." it than says that models will "typically" interact with your database.

I like the loose definition that CodeIgniter uses for models, because it allows me to create models for dealing with any dataset. Want to use an RSS feed as a data source? You could use a model for that. Want to pull data from a webservice? You could use a model for that. You have the freedom to define how you use models.

I'd say the most important thing is consistency. Choose one method and use it consistently throughout your project. If you're working with other developers on the project, it may be better to use the instance methods. That way they won't get confused about what's going on when they compare working code on your site to the CodeIgniter documentation. That, of course, depends on the skill level of the devs you work with.

bradym
+1  A: 

To answer your question directly - the get_instance() function call is the proper way to do what you're trying to do from within a static function.

Jessedc