WP-API/WP-API — pull request #33 by rmccue (2013-12-09 13:10:00+00:00)
Title: Add response object

Setting response data directly via the server acts like a form of global state. It makes it much harder to embed requests in each other (e.g. `/post/2` embeds a call for its post parent to `/post/1`), since the headers are always sent. This is a little crappy, since the API is designed to be composible, and this is standing in the way of that.

However, we don't want this to be overly complicated to use. The benefit of returning raw data is you can work with it easily.

## Proposal

* A new `WP_JSON_ResponseInterface` interface which can be returned from any endpoint with the following methods:
* `get_headers()` - Returns an array of headers which can be sent
* `get_status()` - Returns an integer code for HTTP response status
* `get_data()` - Returns whatever data it's encapsulating
* `jsonSerialize()` - A wrapper to call `get_data()` in most cases, allowing this interface to work right off the bat after #24 is merged, without changing the server classes
* A new `WP_JSON_Response` class which implements `WP_JSON_ResponseInterface` and adds the following methods:
* `__construct($data, $status = 200, $headers = array())`
* `header($key, $value, $replace = true)` - Set a single header (replaces `WP_JSON_Server::header()`)
* `link_header($rel, $link, $other = array())` - Set a single link header (replaces `WP_JSON_Server::link_header()`)
* `set_headers($headers)` - Set all headers
* `set_status($code)` - Set the status code (replaces `WP_JSON_Server::send_status`)

After #24 is merged, this can be dropped in with no changes, but will only send the data. We can then work on moving all the status/header **setting** code to the response object, and the **sending** code to the server.

## Bad Parts
* Makes it slightly harder to use the response (you have to use `$response->get_data()` instead of just `$response`) - On the other hand: You can now access extra data that you couldn't before (status/headers)
* We still need special handling for `WP_Error` - Maybe someday `WP_Error` can extend `WP_JSON_ResponseInterface` :thought_balloon:

Further feedback much appreciated.