Welcome Guest, Not a member yet? Register   Sign In
Load DB results to object
#1

[eluser]nZac[/eluser]
See initial post here: http://ellislab.com/forums/viewthread/193667/
Code:
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:

Code:
// add the data to the object
        $this->_data_seek(0);
        $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:

Code:
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.

Cheers,
AckToon




Theme © iAndrew 2016 - Forum software by © MyBB