• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Load DB results to object

See initial post here: http://ellislab.com/forums/viewthread/193667/
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 $user)
   echo $row->name; // call attributes
   echo $row->reverse_name(); // or methods defined on the 'User' class

User Guide Document Here

So I was doing some digging and I found that when you load a result to an object it puts the fields in the object exactly as they are, but I define the certain variables in the class as private (this breaks the DB_result.php code, as seen here:

// add the data to the object
        $result_object = array();
        while ($row = $this->_fetch_object())
            $object = new $class_name();
            foreach ($row as $key => $value)
                $object->$key = $value;
            $result_object[] = $object;

I get an error similar to: Fatal error: Cannot access private property User::$name in /ci/system/database/DB_result.php on line 83 With User looking like:

class User {
    private $name;

A proposed fix (have not tested) to this could be to add a check in the custom_result_object function of DB_result for public/private properties. If the property attempting to be set is public, set it. If not look for a setter method (some standard would have to be made, maybe setPropertyName) and use that, if neither, fail gracefully (log message).

Thoughts and comments welcome. It should be easily implemented with object_get_vars call.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

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