Slim framework unable to encode to json with protected variables Slim framework unable to encode to json with protected variables json json

Slim framework unable to encode to json with protected variables


Slim's Response::withJson() doesn't do anything magic. It relies on the PHP function json_encode() to do the encoding. json_encode() also doesn't know any special trick. If you pass an object to it to encode it gets all the data it can get from it. And that means only its public properties because, well, this is how OOP works.

However, if you implement the JsonSerializable interface in a class then you can control what data is available to json_encode() when it comes to encode an object of that class.

For example:

class ServerEntity implements JsonSerializable{    private $id;    private $serverName;    // ... your existing code here    public function jsonSerialize()    {        return array(            'id'   => $this->id,            'name' => $this->serverName,        );    }}

Some test code:

echo(json_encode(new ServerEntity(array('id' => 7, 'name' => 'foo'))));

The output is:

{"id":7,"name":"foo"}


In short, an object can be converted into an array.

The object's public properties will be used as $key => $value pairs in the array.

Since the properties are protected, the values are not included.

While it would seem logical that the array actually be empty, the process in which PHP converts the object to an array is not really documented well enough.

In practice what I would recommend is you create a public method that converts the Object to an array.

class ServerEntity { //...    public function toArray() {         return array("id" => $this->id, "name" => $this->name);    } //...}

Then you may simply do...

$app->get('/api/server_list', function ($request, $response, $args) {    $serverlist = new ServerListing($this->db);    $servers = $serverlist->getServers();    $objects = array();    foreach ($servers as $server) {        $objects[] = $server->toArray();    }    $newResponse = $response->withJson($objects);    return $newResponse;    });