An output handler is responsible to transform and render the data according to a desired format.
It should also provide the content mime type format that will be sent to the requester.
To build a custom output handler the developer must extend wlRestOutputHandler class and overwrite the wlRestOutputHandler::render and wlRestOutputHandler::getContentType methods.
class timestampSampleOutputHandler extends wlRestOutputHandler { public function render($data) { $data = wlRestUtils::encodeToArray($data); //make sure the data is an array $data['timestamp'] = date('Y m d H:i:s'); //add the timestamp column to the array return json_encode($data); //encode and deliver the data in JSON format } public function getContentType() { return 'application/json'; //the content type } }
By default the content type is 'text/html', so wlRestOutputHandler::getContentType must be redefined only if serving different mime type is desired.
In this sample the content type is 'text/html' and wlRestOutputHandler::getContentType is not necessary to be redefined.
class csvSampleOutputHandler extends wlRestOutputHandler { public function render($data) { $data = wlRestUtils::encodeToArray($data); //make sure the data is an array $ret = ''; foreach($data as $value) { $ret.=($value.','); } $ret.='EOF'; return $ret; } }
To make it available for a REST service, the custom output handler must be registered along with the extensions using wlRestService::registerOutputHandler.
$service->registerOutputHandler(new csvSampleOutputHandler(array('csv', 'sv')));
Writing output handlers for PHP Rest Services to alter and deliver the data in a custom format is very easy: just redefine the two methods and the rest is done automatically by the base class.
Building a RESTful web service for your PHP web application has never been so easy!
WiseLoop PHP REST Services is a powerful API framework that allows easy development of any kind of API through RESTful web services.