PHP使用soap建立web services

SOAP是PHP5新增的擴展,文件中說明這個擴展只是試驗性,也代表著將來有機會作出變更。
如果發現無法使用soap,可以下載php_soap.dll,並安裝到PHP.

1.建立soap_server.php

/**
* A simple math utility class
* @author John Coggeshall john@zend.com
*/
class math {
/**
* Add two integers together
*
* @param integer $a The first integer of the addition
* @param integer $b The second integer of the addition
* @return integer The sum of the provided integers
*/
public function add($a, $b) {
return $a + $b;
}

/**
* Subtract two integers from each other
*
* @param integer $a The first integer of the subtraction
* @param integer $b The second integer of the subtraction
* @return integer The difference of the provided integers
*/
public function sub($a, $b) {
return $a - $b;
}

/**
* Div two integers from each other
*
* @param integer $a The first integer of the subtraction
* @param integer $b The second integer of the subtraction
* @return double The difference of the provided integers
*/
public function div($a, $b) {
if($b == 0) {
throw new SoapFault(-1, "Cannot divide by zero!");
}
return $a / $b;
}
}
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$server = new SoapServer('math.wsdl', array('soap_version' => SOAP_1_2));
$server->setClass("math");
$server->handle();
注意事項:
1.math class是即將公開的web service.
2.是$server->setClass,而不是$server->addClass.
3.使用ZendStudio對這個檔案制作WSDL,並存成math.wsdl
4.於生成的wsdl file中soap:address location設成server的完整路徑,例如本例子:http://localhost/soap_server.php

操作剛剛建立的web service

//$client = new SoapClient('http://localhost/php/soap/math.wsdl');
$client = new SoapClient("http://localhost/php/soap/soap_server.php?WSDL");
try {
$result = $client->div(8, 2); // will cause a Soap Fault if divide by zero
print "The answer is: $result";
} catch(SoapFault $e) {
print "Sorry an error was caught executing your request: {$e->getMessage()}";
}
程式碼中被註釋的部份,代表也可以使用靜態的WSDL文件創立$client,但是這樣必須手動生成WSDL文件。

沒有留言: