Implementing clients with WSF/PHP is very simple. Here is the code to list the books.
<?php $requestPayloadString = <<<XML <getBooks> <book/> </getBooks> XML; try { $client = new WSClient( array("to" => "http://localhost/rest/09/library.php/book", "useSOAP" => FALSE, "HTTPMethod" => "GET")); $responseMessage = $client->request($requestPayloadString); printf("Response = %s <br>", htmlspecialchars($responseMessage->str)); } catch (Exception $e) { if ($e instanceof WSFault) { printf("Error String: %s\n", $e->str); printf("HTTP Code : %s\n", $e->httpStatusCode); } else { printf("Message = %s\n",$e->getMessage()); } } ?>
There is a PHP class named WSClient
that comes with WSO2 WSF/PHP. While creating the client object instance you can provide an array of options. The options could include the endpoint address of the service, the "to"
option. To make use of REST you have to set the "useSOAP"
to FALSE
. You can also specify the HTTP method to be used with "HTTPMethod"
option.
$client = new WSClient( array("to" => "http://localhost/rest/09/library.php/book", "useSOAP" => FALSE, "HTTPMethod" => "GET"));
Then you send the request and receive the response.
$responseMessage = $client->request($requestPayloadString);
In this sample the request payload could be empty but in case you want to send a set of query parameters, you can provide that as XML and the framework would encode that into a series of query parameters.
Finally, you can consume the response.
printf("Response = %s <br>", htmlspecialchars($responseMessage->str));
If there are any errors, you can use the exception model to deal with them with WSO2 WSF/PHP. In this sample, we have a try
catch
block.
} catch (Exception $e) { if ($e instanceof WSFault) { printf("Error String: %s\n", $e->str); printf("HTTP Code : %s\n", $e->httpStatusCode); } else { printf("Message = %s\n",$e->getMessage()); } }
In case of errors, the framework would compose the error message to a WSFault
instance.
Next we will see the client code that adds books.
<?php $requestPayloadString = <<<XML <books> <book><name>Book7</name><author>Auth7</author><isbn>ISBN0007</isbn></book> <book><name>Book8</name><author>Auth8</author><isbn>ISBN0008</isbn></book> </books> XML; try { $client = new WSClient( array("to" => "http://localhost/rest/09/library.php/book", "useSOAP" => FALSE, "HTTPMethod" => "POST")); $client->request($requestPayloadString); } catch (Exception $e) { if ($e instanceof WSFault) { printf("Error String: %s\n", $e->str); printf("HTTP Code : %s\n", $e->httpStatusCode); } else { printf("Message = %s\n",$e->getMessage()); } } ?>
The only differences in this client code and the previous GET
client is the fact that we use a different XML request payload expected by the add
operation. We use HTTP
POST
method instead of GET
and the fact that we are not expecting a response from the server.