PHP RestServer Class

Why send and receive ‘heavy’ SOAP messages if we can do it RESTfully with JSON. The problem for me was that I wanted to build my PHP web service in a layered style and simply expose the methods in the top-most class and let that class interact with all of the underlying API. This would give me control over what functionality the client applications have access to but I didn’t want to create separate files for each function in order to be RESTful.

To allow the RESTful exposure of the functions in a given class, I developed RestServer. It works as follows.

 require_once "RestServer.php";

 $rest = new RestServer(Hello);

 class Hello
   public static function sayHello($name)
      // RestServer will encode return objects as JSON
      return array("Response" => "Hello, " . $name);

That’s all there is to it. Now the ‘sayHello’ method is exposed for client side consumption. Consuming the service is just as simple.

UPDATE: The RestServer class has been updated to make it even more robust. The method names and request parameter keys are now case-insensitive. Perhaps even better, it also no longer matters what order the key/value pairs appear in the request. If you do ?method=myMethod&name=Jake OR ?NaMe=Jake&MetHod=mymethOD you will get the same result.

Download the code and examples at GitHub.