6

I'm looking for proper way to organize 'Result object classes' in CodeIgniter. These classes are usualy used in models as described in documentation:

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result('User') as $row)
{
   echo $row->name; // call attributes
   echo $row->reverse_name(); // or methods defined on the 'User' class
}

So, where to put 'User' class and is there any 'offical' way how to load it?

sasa
  • 2,443
  • 5
  • 23
  • 35

2 Answers2

3

Try using a library.

Place your class in the application/libraries folder, then use the loader to load it:

$this->load->library('user');
Silviu G
  • 1,241
  • 10
  • 31
  • Absolutly not, because that will create new instance of user class and I don't want to have that empty object in memory. And of course, result object classes aren't libraries at all. – sasa Sep 17 '12 at 12:35
  • The use $this->load file() to load a php file containing your classes – Silviu G Sep 17 '12 at 14:04
0

Not exactly what you are asking for, but I often use a MY_Model with:

public function merge_object(&$object, $data){

    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    if (!empty($data)) {
        foreach ($data as $property => $value) {
            if (!property_exists($object, $property)) {
                $object->$property = $value;
            }
        }
    }
    return $object;
}

and then call $this->merge_object($this, $data); from the __construct($data = array())

When you call a model function now, it returns a an instance of the model class as well, and so you can access any of its methods. It does essentially what you are trying to do.

jmadsen
  • 3,635
  • 2
  • 33
  • 49