PHP REST Services

PHP REST Services

RESTful web service API framework for PHP

Creating output handlers

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.

Sample 1. Adding a timestamp to data and deliver it in JSON format

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
    }
 }

Sample 2. Rendering the data in very basic CSV format

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.

Regular License $10.00
Use by you or one client, in a single end product which end users are not charged for.

Extended License $50.00
Use by you or one client, in a single end product which end users can be charged for.

Short Information

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.

Buyer rating:
348 Sales