Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4023986
  • 博文数量: 626
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 11080
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-23 13:08
文章分类

全部博文(626)

文章存档

2015年(72)

2014年(48)

2013年(506)

分类: PHP

2013-09-25 10:08:27

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)。

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 = <<
  $result
XML;
$returnMsg = new WSMessage($response);
return $returnMsg;
}

$service = new WSService(array("operations" => array("calculate")));
$service->reply();
?>
一旦部署后,可以从http://localhost:/CalculatorService.php访问它。

第三步:编写计算器客户端
编写一个客户端,调用此计算器服务,并打印结果。
该脚本命名为CalculatorClient.php,且放入Apache HTTP服务器的web root。
不要忘了改变Apache服务器的端口(即http://localhost:81/CalculatorService.php)来匹配服务器。

$requestPayload = <<

100
43
add

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:/CalculatorService.php

以上只是创建计算器服务的基本例子。
阅读(2164) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~