Team LiB
Previous Section Next Section

Consuming Web Services

The service alone does not show anything useful in the Web browser; as Figure 18.3 demonstrates, we get an error message. The reason is obvious: We just called the Web service's URL but did not send a SOAP request, so the service rightfully complains that there was a "Bad Request."

Figure 18.3. No request, no result.


Therefore, we need a client to actually use the code (and retrieve the desired GUID). For this task, the SOAP extension of PHP 5 offers an easy way to access a Web service, as long as you have its WSDL description. The SoapClient object takes the filename of a WSDL description in its constructor and then creates a proxy object. This is a local object that behaves exactly like the remote service. The advantage is that you can work with the service as if it is a local object, without having to care about opening socket connections, creating and parsing SOAP, and the like.

Querying the Web service basically comes down to two lines of code. In Listing 18.3 we have one more line, which disables the WSDL cache.

Listing 18.3. A SOAP Client for the getGuid() Method
<?php
  ini_set('soap.wsdl_cache_enabled', 'Off');

  $soap = new SoapClient('guid.wsdl');
  echo $soap->getGuid('PHP_');
?>

Figure 18.4 shows the result: The GUID is sent back to the client.

Figure 18.4. A GUID provided by the Web service.


However, much more sophisticated possibilities are in the class. One is error handling. For instance, we would require that the prefix parameter is not null and also not an empty string or other whitespace. If these conditions are not met, an error is returned. The built-in error object for SOAP is SoapFault. Listing 18.4 shows the updated Web service server, this time also returning a SOAP error.

Listing 18.4. The SOAP Server Returns an Error if No Prefix Is Provided
<?php
  ini_set('soap.wsdl_cache_enabled', 'Off');

  function getGuid($prefix) {
    if (!isset($prefix) || trim($prefix) == '') {
      throw new SoapFault('Server', 'No prefix provided.');
    } else {
      return uniqid($prefix);
    }
  }

  $soap = new SoapServer('guid.wsdl');
  $soap->addFunction('getGuid');
  $soap->handle();
?>

Listing 18.5 contains the updated client script that now also checks for a SOAP error using try...catch.

Listing 18.5. A SOAP Client with Error Handling
<?php
  ini_set('soap.wsdl_cache_enabled', 'Off');

  $soap = new SoapClient('guid.wsdl');

  try {
    echo $soap->getGuid('PHP_');
  } catch (SoapFault $ex) {
    echo $ex->faultstring;
  }
?>

If you change the call getGuid('PHP_') to getGuid(), the SOAP server returns an error message that is shown in Figure 18.5.

Figure 18.5. An error message triggered by a missing or invalid parameter.


    Team LiB
    Previous Section Next Section