PHP開發Web服務
WSO2 WSF/PHP(WSO2 Web Services Framework/PHP,WSO2 Web服務架構) 是一個PHP擴充,允許用來建立和使用Web服務。它支援SOAP1.1、SOAP1.2、MTOM、Web服務尋址、Web服務安全,也支援REST風格的調用。WSO2 WSF/PHP最新的版本(v2.0.0)剛釋出。
下面是一個簡短的指南解釋了怎樣用WSO2 WSF/PHP擴充建立一個簡單的電腦服務。
(假設:Apache HTTP伺服器已經安裝在你的機器上,且你基本熟悉在Apache伺服器上運作PHP腳本)
第一步:安裝WSO2 WSF/PHP擴充
在Ubuntu下,有下列步驟:
1. apt-get install php5
2. apt-get install php5-dev
3. apt-get libapache2-mod-php5
3. apt-get install libxml2
4. apt-get install libxml2-dev
5. 下載下傳 WSF/PHP v2.0.0 并解壓到一個目錄
6. 在指令行通路該目錄,以“root”執行下列指令:
./configure
make
make install
7. /etc/init.d/apache2 restart
第二步:編寫電腦服務
建立一個名為CalculatorService.php的腳本,且放入Apache HTTP伺服器的web root(通常是 /var/www)。
<?php
function calculate($inMessage){
$simplexml = new SimpleXMLElement($inMessage->str);
$operand1 = $simplexml->param1[0];
$operand2 = $simplexml->param2[0];
$operation = $simplexml->param3[0];
if($operation != null)
{
switch($operation)
{
case "add" : $result= $operand1 + $operand2; break;
case "sub" : $result= $operand1 - $operand2; break;
case "mul" : $result= $operand1 * $operand2; break;
case "div" : $result= $operand1 / $operand2; break;
}
}
$response = <<<XML
<result>$result</result>
XML;
$returnMsg = new WSMessage($response);
return $returnMsg;
$service = new WSService(array("operations" => array("calculate")));
$service->reply();
?>
一旦部署後,可以從http://localhost:<port>/CalculatorService.php通路它。
第三步:編寫電腦用戶端
編寫一個用戶端,調用此電腦服務,并列印結果。
該腳本命名為CalculatorClient.php,且放入Apache HTTP伺服器的web root。
不要忘了改變Apache伺服器的端口(即http://localhost:81/CalculatorService.php)來比對伺服器。
$requestPayload = <<<XML
<calculate>
<param1>100</param1>
<param2>43</param2>
<param3>add</param3>
</calculate>
try{
$message = new WSMessage($requestPayload,
array("to" => "http://localhost:81/CalculatorService.php"));
$client = new WSClient();
$response = $client->request($message);
echo "Answer : $response->str";
catch (Exception $e){
if ($e instanceof WSFault){
$fault = $e;
printf("Soap Fault received. Code: '%s' .Reason: '%s'/n",
$fault->code, $fault->reason);
}else{
printf("Exception occurred. Message: '%s'/n", $e->getMessage());
第四步:通路服務
通過執行CalculatorClient.php通路服務,如下:
http://localhost:<port>/CalculatorService.php
以上隻是建立電腦服務的基本例子。