当前位置: 首页 > 工具软件 > WSO2 WSF/PHP > 使用案例 >

[b]PHP开发Web服务[/b]

韩华美
2023-12-01
[align=center][b]PHP开发Web服务[/b][/align]
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)来匹配服务器。
<?php
$requestPayload = <<<XML
<calculate>
<param1>100</param1>
<param2>43</param2>
<param3>add</param3>
</calculate>
XML;

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

以上只是创建计算器服务的基本例子。
 类似资料: