Dealing with Payloads

Monday, January 7, 2008

Last week, I talked about getting a simple service and client working. However, these samples did not dig into the details of dealing with the payload.

Payload is the business logic specific content sent within the SOAP body of the SOAP message. Let us look into a sample where a number is given to calculate the factorial. The client sends the number and the service calculates the factorial and returns the result.

Here is the payload that the client sends:



Now the service needs to understand the incoming payload and pick the param to calculate the result. Here is the code for the operation:

  1. function getFactorial($message) {


  3. $simplexml = new SimpleXMLElement($message->str);

  4. $value = $simplexml->param[0];


  6. $result = factorial($value);


  8. $responsePayloadString = <<<XML

  9. <getFactorialResponse>

  10. <result>$result</result>

  11. </getFactorialResponse>

  12. XML;


  14. return $responsePayloadString;

  15. }

On line 3, we create a SimpleXMLElement instance, using the incoming payload. Line 4 access the param value within the payload. This means that the service needs to have some understanding about the format of the incoming payload in order to process it. The rest of the logic in the function implementing the operation is simple. On line 6, factorial is calculated for the incoming param value and form line 8 to 12, the response payload is prepared with the result. Finally on line 14, we return the response payload.

The response payload would look something like:




The client too can process the response payload in a way similar to how it was done on server side.

  1. $response = $client->request($reqestPayloadString);


  3. $simplexml = new SimpleXMLElement($response->str);


  5. echo "Result = ".$simplexml->result[0]."\n";

Create SimpleXMLElement instance out of the response and access the result element.

Now you know how to deal with incoming payloads both on client as well as on server side.

No comments: