We recommend that you support more than one format - that you push things out in one format and accept as many formats as necessary. You can usually automate the mapping from format to format. ... We recommend the fourthsquare approach To get the JSON format from a collection or specific element:
dogs.json
/dogs/1234.json
For me this means checking which ending the request has and return either json or xml:
class Item {
var $outformat = 'json', $content = NULL;
function __construct($f3){ if ( strpos(basename($f3->get('PATH')),'.xml') ) $this->outformat='xml'; }
function get($f3) { $this->content = array ('black' => 'dog','white' => 'sheep'); }
function post(){}
function put(){}
function delete(){}
function afterroute (){
if($this->outformat == 'xml'){ header('Content-Type: text/xml'); $xml = new SimpleXMLElement('<root/>'); array_walk_recursive($this->content, array ($xml, 'addChild')); die(print $xml->asXML()); }
header('Content-Type: application/json'); die(json_encode($this->content)); }}
$f3->map('/cart/@item','Item');
My questions,
- is there some F3 var which already holds the extension of the last param (.json || .xml) [see constructor]?
- is there a better (F3´ish) pattern than this with __construct and afterroute()
print_r($f3->hive())
you can maybe create a parent BaseApi class with a beforeroute (instead of the constructor) and afterroute then have your api classes extend that?
When a client intercepts HTTP error codes
1 - Use suppress_response_codes = true
2 - The HTTP code is no longer just for the code
3 - Push any response code that we would have put in the HTTP response down into the response message
is there some F3 var which already holds the extension of the last param?
[maps]
/dogs.@ext = Controllers\Dogs
function afterroute($f3,$params) {
switch($params['ext']) {
case 'json':
// output json
case 'xml':
// output xml
default:
$f3->error(404);
}
}