In this conclusion to a five-part article series on Web Services, you'll learn how to create a SOAP server, add server functions, and more. This article is excerpted from chapter 20 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Although the addFunction() method works fine for adding functions, what if you want to add class methods? This task is accomplished with the setClass() method. Its prototype follows:
Theclass_nameparameter specifies the name of the class, and the optionalargs parameter specifies any arguments that will be passed to a class constructor. Let’s create a class for the boxing quote service and export its methods usingsetClass():
<?php class boxingQuotes { function getQuote($boxer) { if ($boxer == "Tyson") { $quote = "My main objective is to be professional but to kill him. (2002)"; } elseif ($boxer == "Ali") { $quote = "I am the greatest. (1962)"; } elseif ($boxer == "Foreman") { $quote = "Generally when there's a lot of smoke, there's just a whole lot more smoke. (1995)"; } else { $quote = "Sorry, $boxer was not found."; } return $quote; } }
The decision to usesetClass()instead ofaddFunction()is irrelevant to any requesting clients.
Directing Requests to the SOAP Server
Incoming SOAP requests are received by way of either the input parameter soap_request or the PHP global $HTTP_RAW_POST_DATA. Either way, the method handle() will automatically direct the request to the SOAP server for you. Its prototype follows:
void SoapServer->handle([string soap_request])
It’s the last method executed in the server code. You call it like this:
$soapserver->handle();
Persisting Objects Across a Session
One really cool feature of the SOAP extension is the ability to persist objects across a session. This is accomplished with the setPersistence() method. Its prototype follows:
void SoapServer->setPersistence(int mode)
This method only works in conjunction withsetClass(). Two modes are accepted:
SOAP_PERSISTENCE_REQUEST: This mode specifies that PHP’s session-handling feature should be used to persist the object.
SOAP_PERSISTENCE_SESSION: This mode specifies that the object is destroyed at the end of the request.