Wednesday, April 15, 2009

Building a REST Service in PHP

OK, I'm a big fan of using the right tool for the job. Daily I switch between Rails, Java and PHP. Rails is probably the easiest to use for developing a REST Service, but sometimes you don't want the overhead of a rails server and you want that feel good all over sense of stability that LAMP gives you.

First, I created an alias to send all requests to a single php file (service.php).

AliasMatch /Beers/.* /var/www/www.liquidmirth.com/service.php

This sends all http://www.liquidmirth.com/Beers/* requests to service.php. Then, I created a generic service class. This grabs the method, id and the target object from the url, and uses reflection to invoke the appropriate method on a service class. The code for the service.php class is below.


include 'beer.php';
header('Content-Type: text/xml');
$method = strtolower($_SERVER["REQUEST_METHOD"]);
$object = $_SERVER["REQUEST_URI"];
$object = substr($object, 1, strlen($object)-1);
$vars = explode("/", $object);
$object = $vars[0];
$id = $vars[1];
// echo "method ==> (".$method.")
";
// echo "object ==> (".$object.")
";
// echo "id ==> (".$id.")";
$method = new ReflectionMethod($object, $method);
echo $method->invoke(NULL, $id);


In the above code, the request is received, the Beer object is created and the get() method is invoked on that object with the id supplied as a parameter. So, when http://www.liquidmirth.com/Beer/1234 is requested. Beer->get(1234) is invoked.

Its that simple.

No comments: