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.

Wednesday, April 8, 2009

Fixing Sendmail (dead.letter issue)

OK, we have lots of machines that we host out on slicehost. We want them to be part of our domain (foo.ourdomain.com). So, we configure their hostname to be that. Unfortunately, we want them to be able to send mail to people in our domain (john@ourdomain.com). Since the machine thinks it is part of the domain, it looks for that user, can't find them and consequently fails to send the mail out.

Testing sendmail, it always drops the mail into dead.letter immediately.

To fix this, I simply edited /etc/mail/sendmail.cf and uncommented the domain, setting it to some fictitious name (since the machine won't be the destination for any mail.

I uncommented this line:
Dj$w.Foo.COM