Creating a REST Web Service
From Photon Framework
Let's start by creating a Service class for a calendar system. To keep the Service API consistent, all service methods will take input parameters (associative array), and will respond with a response (associative array).
<source lang="php"> <?php class EventService {
function addEvent ( $params ) {
// create event from the $params array somehow (INSERT statement, Propel peer, etc)
$event_id = createEventFromArray( $params );
// return a response (associative array) with the id of the newly created event in the body
return array(
'body' => $event_id
);
}
function getEvent ( $params ) {
// get the event by the id somehow (SELECT statement, Propel, etc)
$event = getTheEventSomehow($params['event_id']);
// return a response (associative array) with the event in the body.
return array(
'body' => $event
);
}
function getEvents ( $params ) {
// get events based on criteria from the params array,
// might use max number of events, page, type of event, etc
// get a count first $count_of_events = countEventsMatchingCriteria( $params['event_type'] );
// now get the events // probably sql based on $params $events = getEventsMatchingCriteria( $params['event_type'], $params['limit'], $params['offset'] ;
// return a response
return array(
'total' => $count_of_events,
'body' => $events
);
}
} </source>
Next we will create a RestServer: <source lang="php"> <?php require 'photon/rest/RestService.php'; require 'EventService.php';
$server = new RestServer(); $server->addService(
'EventService', array( 'post:/services/events/add' => 'addEvent', 'get:/services/events/@event_id' => 'getEvent', 'get:/services/events' => 'getEvents' )
); $server->setFormat('json'); $server->run(); </source>
The RestServer will map each of the urls to the method that is supposed to respond to it on the service. It will also translate the response to the specified format, json in this case.
Any string between slashes that starts with an @ sign will be treated as a param variable. So, if a route is defined as:
post:/services/events/@event_id/attendants => getEventAttendants
and the url requested is
/services/events/242/attendants?type=programmers
the getEventAttendants method will be called with the following $param array as follows:
$param = array('event_id'=>'242', 'type'=>'programmers');
so the getEventAttendants can use those values to create an sql query.
Generally I store the url arrays inside of the service classes as a static property:
<source lang="php">
<?php
class EventService {
static $urls = array( 'post:/services/events/add' => 'addEvent', 'get:/services/events/@event_id' => 'getEvent', 'get:/services/events' => 'getEvents' );
...
} </source> and then reference them on the RestServer:
$server->addService('EventService', EventService::$urls);
I think it makes for cleaner code.
