PHP

Creating a Web Service with PHP 5's SOAP Extension

One of the key features of PHP 5 is the new SOAP extension. Because it is written in C, it is much faster than anything that is coded in PHP alone. However, the extension is relatively new, so there are still some hiccups and missing features. However, it works well on many occasions.

You have to configure PHP with enable-soap to use the extension; Windows users have to add extension=php_soap.dll to their php.ini configuration file. Then, the extension is available and writing a SOAP server is quite easy.

Again, it's a small number of steps: Instantiate the SoapServer class, add your function with addFunction(), and, finally, call handle().

A Web Service with PHP5-SOAP

<?php
  $soap = new SoapServer(null, array('uri' =>
    'http://php.hoshmand.org/'));
  $soap->addFunction('add');
  $soap->handle();
  function add($a, $b) {
    return $a + $b;
  }
?>

PHP 5-SOAP originated as a PECL extension. So, it is also possible to use this extension under PHP 4, just grab the code from CVS. However, no precompiled Windows binaries are available at the moment, and chances are that there never will be any.

Automatically Generating WSDL with PHP 5's SOAP Extension

The greatest shortcoming of PHP5-SOAP is that there is no way to automatically generate WSDL with it. This is not often mentioned; however, it does create problems in real life. WSDL is so complicated that errors in the WSDL are hard to see and even harder to find.

However, you can create such a WSDL description for a Web Service in several ways, most of which have been used in real-world projects:

  • Use NuSOAP or PEAR::SOAP to create a similar service, just to get the WSDLjust change the <soap:address> element

  • Use the class Ctrx_SOAP_AutoDiscover (available at http://crtx.org/index.php?area=Main&page=CrtxSoapAutoDiscover)

  • Use the Webservice Helper tool (available at http://www.jool.nl/new/index.php?file_id=1)

  • Use the WSDL_Gen class (available at http://www.schlossnagle.org/~george/php/WSDL_Gen.tgz)

So as you can see, WSDL support is being worked on, not as part of the SOAP extension itself, but in the form of external projects. But hopes are that this will change some day.

If you finally have a WSDL description of your service (in the download archive, you will find a file AddService.wsdl that originated from the PEAR::SOAPgenerated WSDL), the code for the server must only be slightly updated. The first parameter for the SoapServer instantiation receives the WSDL URL; also, the method(s) of the Web Service must be put in a class. Then, setClass() provides the SOAP extension with the name of the class to be used.

<?php
  $soap = new SoapServer(
    'AddService.wsdl',
    array('uri' => 'http://php.hoshmand.org/')
  );
  $soap->setClass('ServiceClass');
  $soap->handle();
  class ServiceClass {
    function add($a, $b) {
      return $a + $b;
    }
  }
?>

by BrainBellupdated
Advertisement: