Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^308) CHAPTER 20 ■ ADVANCED WEB SERVICES


Objects and Persistence


Until now, you have been using simple functions to handle the operations in your web service.
You can, however, create a class to achieve the same results. Instead of specifically adding func-
tions to the SOAP client, you can use setClass() to register an entire class of methods. Each
method will automatically map to the corresponding WSDL operation. This saves you from
having to register each method separately and can help you better encapsulate your web services.
Listing 20-8 demonstrates using an object to handle SOAP requests.

Listing 20-8. Using an Object to Handle SOAP Requests

<?php

class Service {
function Demo($param1) {
session_start();
if(!array_key_exists('counter', $_SESSION)) {
$_SESSION['counter'] = 1;
}
return $_SESSION['counter']++;
}
}

ini_set('soap.wsdl_cache_enabled', '0');
$server = new SoapServer('demo.wsdl');
$server->setClass("Service");
$server->handle();

Under normal operation, this class will get instantiated and destroyed with each SOAP call.
However, this is not usually desirable, as classes tend to track properties between method calls,
and there is not a lot of benefit to creating an object instance with each method call.
Ignoring the performance implication, you could use sessions to track information between
calls, but there is a better way. This ability is called persistence, and it allows you to initialize a
class once and have it automatically serialized between requests to the service.
Replacing only service.php with the code from Listing 20-9, you can use the persistence
mode without using session_start() or $_SESSION variables. From a SoapServer perspective,
the method that turns on persistence mode is setPersistence() with either the constant SOAP_
PERSISTENCE_REQUEST (the default, normal mode) or the constant SOAP_PERSISTENCE_SESSION.

Listing 20-9. Persistence Mode (service.php)

class Service {

private $counter=1;

function Demo($param1) {
return $this->counter++;
}
}

McArthur_819-9.book Page 308 Friday, February 29, 2008 8:03 AM

Free download pdf