fuel / core

Fuel PHP Framework - The core of the Fuel v1 framework
http://fuelphp.com
813 stars 345 forks source link

REST controller with json - empty output! #29

Closed dhrrgn closed 13 years ago

dhrrgn commented 13 years ago

There's a bug with JSON output in a REST controller. Here's some code:

class Controller_API extends Controller_Rest {
    public function get_list()
    {
        $users = Model_User::find('all');
        //print_r($users)
        $this->response($users);
    }
}

This will output:

{ 1: { } 2: { } }

I have two users in my test environment, so having 2 json values would be correct, but they're empty. By uncommenting the print_r I get my 2 results so the $users variable is correct.

Also, if I change config/rest.php back to xml, it outputs everything correctly. More details here: http://fuelphp.com/forums/topics/view/974

dhrrgn commented 13 years ago

Making this a Bug. It was submitted by koichi h Today.

koichirose commented 13 years ago

Commenting to be notified of changes.

jschreuder commented 13 years ago

I'm speculating here but I think the problem is this line: https://github.com/fuel/core/blob/develop/classes/format.php#L215

My assumption is that json_encode() will run a get_object_vars() on the Model_User object, which will return an empty array as all the properties are protected or private. The way this could be solved is by doing something like this:

// Encode as JSON
public function to_json()
{
    $data = $this->_data instanceof ArrayAccess ? $this->to_array($this->_data) : $this->_data;
    return json_encode($data);
}

Or do this by converting objects to arrays with a _from...() method that can use either get_object_vars() or the above solution.

jschreuder commented 13 years ago

As it currently doesn't work at all I submitted my fix, don't have the time to properly test it though.