The simplest PHP Web Service

Tuesday, January 1, 2008

I was writing an article on getting started with PHP Web services last few days, and I came up with this simple service to explain the minimal steps you need with WSO2 Web services framework to implement a service.

  1. <?php  
  2. function knock($message) {
  3.     $responsePayloadString = <<<XML
  4.             <knockResponse>Who is there?</knockResponse>  
  5. XML;
  6.     return $responsePayloadString;
  7. }

  8. $service = new WSService(array("operations" => array("knock")));

  9. $service->reply();

  10. ?>

This code could be broken into three main logical parts.

  1. Function implementing the service operation (lines 2 to 7)
  2. Creating service instance (line 8)
  3. Replying to client requests (line 9)
In this Web service, we have one operation named knock. As you can see on line 8, when the WSService instance is created, the set of operation could be given as an array. In this example, we have only one operation, hence there is only one element given in the operations array.

In this example, the function that implements the operation knock is function knock. This function takes an input parameter (line 2). This input parameter contains the request sent by the client, however in this example, we are not interested in the content of the request, hence we are not looking into the incoming message parameter. The logic implemented in the knock is very simple, we define the XML string to be returned as response (lines 3 to 5) and return the response XML string (line 6).

The call to reply() method of the WSService instance (line 9) triggers processing when there is a request form a client. It will locate the function implementing the invoked service operation, call the function with the incoming request content and prepare the response using the value returned by the function that was called. All these things happen transparent to the user.

No comments: