Home  >  Article  >  php教程  >  利用PHP SOAP扩展实现简单Web Services

利用PHP SOAP扩展实现简单Web Services

WBOY
WBOYOriginal
2016-06-13 09:27:35835browse

利用PHP SOAP扩展实现简单Web Services

WebServices能干什么?

 

WebServices 可以将应用程序转换为网络应用程序。

 

通过使用 WebServices,您的应用程序可以向全世界发布信息,或提供某项功能。

 

 

 

好了,关于WebServices网上资料很多,就不过多介绍了,直接进入主题。

 

PHP有两个扩展类库可以实现WebServices,一个是NuSoap,一个是php官方自带的Soap扩展,在使用上大致都差不多,就拿官方自带的Soap扩展来说吧。

 

在Soap编写WebServices中主要用到了SoapClient,SoapServer,SoapFault三个类。

 

SoapClient:用户访问的类,也就是客户端,使用WebServices的类

 

SoapServer:提供WebServices类,服务端

 

SoapFault:异常处理类

 

 

 

作为示例,写个超级简单的的WebServices来感受下吧,直接代码说话

 

 

 

1、Myself.class.php  --业务逻辑类,功能实现类

 

复制代码

1

2     //业务逻辑类

3     class Myself{

4         public function info(){

5             return "新浪微博:Balla_兔子,求关注啦~";

6         }

7     }

8 ?>

复制代码

很简单,无需多余解释,返回一个字符串。

 

 

 

2、soapServer.php  --服务端类,提供服务

 

复制代码

 1

 2     //服务端

 3     require_once('Myself.class.php');

 4     $parameter=array(

 5         'uri'=>'http://localhost/',

 6         'location'=>'http://localhost/soap/soapServer.php'

 7         );

 8     $soapServer=new SoapServer(null,$parameter);

 9     $soapServer->setClass('Myself');

10     $soapServer->handle();

11 ?>

复制代码

SoapServer有两种操作模式:

 

上面举例的是non-WSDL模式,在实例化SoapServer类时,一个参数是放WSDL文件,在non-WSDL模式里,可以为空,把配置参数以数组的形式写在第二个参数。

 

如果用的是WSDL模式,可以直接用WSDL文件让服务器读取配置参数,此时可以省略第二个数组参数。

 

配置参数有许多,上面为简单举例只列出2个,具体大家可以在网上查查

 

uri  --命名空间

 

location  --服务地址

 

1、WSDL模式  在WSDL模式中,构造器可以使用WSDL文件名作为参数,并从WSDL中提取服务所使用的信息。

 

2、non-WSDL模式  在non-WSDL模式中,使用参数来传递要使用的信息,用来管理服务的行为。

 

 

 

在SoapServer类的众多方法中,有三个方法比较重要。它们是SoapServer::setClass()、SoapServer::addFunction()、SoapServer::handle()。 

 

特别注意,在handle方法之前之后均不能输出任何参数,否则会出错。

 

 

 

3、soapClient.php  --客户端类,使用服务

 

复制代码

 1

 2     //客户端

 3     $parameter=array(

 4         'uri'=>'http://localhost/',

 5         'location'=>'http://localhost/soap/soapServer.php'

 6         );

 7     try{

 8         $soapClient=new SoapClient(null,$parameter);

 9         echo $soapClient->info();

10 

11     }catch(Exception $e){

12         echo $e->getMessage();

13     }

14 

15 ?>

复制代码

SoapClient类可以作为给定WebServices的客户端。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn