php wsdl接口

发布时间:2013-12-10 18:13:56 阅读:1282次
 转:http://www.cnblogs.com/phpdragon/archive/2012/06/10/2544171.html
http://blog.csdn.net/cwt0408/article/details/6955613
最近工作的内容使用到了接口!
对于系统接口:
现下接触的有两种!
 
1、URL类型的接口
 
URL路由带参数式的接口!这个很好做!只要有过Web开发经验的人都能完成!
这种接口数据不够隐蔽性,可以直接在浏览其中看到,
 
如支付宝的交易请求URL。需要加一个MD5签名,和服务器端的再次向支付宝服务器发送验证!
虽然soap方式传递的数据隐蔽性很好!但为了数据安全,难免也需要进行数据签名。
 
2、SOAP类型的接口
 
无关编程语言、无关平台、扩展性很好
 
要实现一个SOAP 型的接口,有两种方式:一种有WSDL文件方式、一中无WSDL文件方式!
 
 
对于热爱研究型的人来说,使用第一种方式可以让你清楚的了解PHP是怎么创建了一个Web Service!
但第一种对于新手来说,创建一个XML格式的WSDL文件,是比较难的,这你的先了解熟悉什么是XML!
学会XML语法!
  但对于一个急于解决问题的人来说!没有这么多的时间去熟悉!所以这是件烦恼的事!
不过不急,上面说了,还有一种无需WSDL文件的方式!而且,本讲解还提供了一个自动生成WSDL文件的类!
 
讲解前,先配置下PHP的soap环境支持:
 
找到php.ini文件
;extension=php_soap.dll
 
删除掉";" ,重启apache服务器
 
 
 
一、有WSDL文件方式
    在这里先介绍标准的webservice。 
那么如何创建wsdl呢?对于PHP来说这确实是件很不容易的事情,有人说用zend studio创建很方便,这是一种方法。但对于那些不喜欢用zend studio的人来说,会觉得创建一个web service还要安装zend studio,太强人所难了。
    在这里介绍一个简单的方法,到网上下载SoapDiscovery.class.php类,里面有个公用方法:getWSDL,这个方法末尾是用的return,那么,你修改一下这个方法: 
//return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, ''); 
//生成wsdl文件,将上面的return注释 
$fso = fopen($this->class_name . ".wsdl" , "w"); 
fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '')); 
现在生成wsdl的类有了,SoapDiscovery.class.php(源码在最末尾)。
 
     再准备一个提供服务的Service.php类文件或者函数就可以创建wsdl了!
 
复制代码
class Service {
 
    public function HelloWorld() {
        return "Hello";
    }
 
    public function Add($a, $b) {
        return $a + $b;
    }
 
}
?> 
复制代码
  创建wsdl文件的creat_wsdl.php
 
复制代码
 
include("Service.php");
include("SoapDiscovery.class.php");
 
$disco = new SoapDiscovery('Service', 'soap'); //第一个参数是类名(生成的wsdl文件就是以它来命名的),即Service类,第二个参数是服务的名字(这个可以随便写)。
$disco->getWSDL();
复制代码
  运行create_wsdl.php文件,此时会生成一个Service.wsdl的文件
 
 
 
  再在Service.php文件中添加一些代码
 
复制代码
 
class Service {
 
    public function HelloWorld() {
        return "Hello";
    }
 
    public function Add($a, $b) {
        return $a + $b;
    }
 
}
 
$server = new SoapServer('Service.wsdl', array('soap_version' => SOAP_1_2));
$server->setClass("Service"); //注册Service类的所有方法 
$server->handle(); //处理请求
 
?> 
复制代码
  创建webservice客户端程序,测试webservice是否有效,文件名是:client.php 
将以下内容拷贝进去:
 
  
 
复制代码
 
 ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
 
  $soap = new SoapClient('http://localhost/Dragon/soap/Service.php?wsdl');
 echo $soap->Add(28, 2);
  echo $soap->__soapCall('Add',array(28,2))//或这样调用
 
复制代码
  OK!测试通过!
 
  
 
 二、无WSDL文件方式
 
   服务器端
 
复制代码
class Service
{
  public function HelloWorld()
   {
      return  "Hello";
   }
  public  function Add($a,$b)
   {
      return $a+$b;
   }
}
$server=new SoapServer(null,array('uri' => "abcd"));
$server->setClass("Service");
$server->handle();
复制代码
   客户端
 
复制代码
  try {
  $soap = new SoapClient(null, array(
  "location" => "http://localhost/Dragon/soap/Service.php",
  "uri" => "abcd", //资源描述符服务器和客户端必须对应
  "style" => SOAP_RPC,
  "use" => SOAP_ENCODED
  ));
 
  echo $soap->Add(12, 2);
  } catch (Exction $e) {
  echo print_r($e->getMessage(), true);
  }
复制代码
  
 
三.出现的问题。
 
1.在方法中对属性的赋值在其他方法中不起作用。
比如在客户端调用服务端某个方法对某个属性赋值。
在其他方法里就不能用。但在 __construct 方法中对属性的赋值是可以个在其他方法中使用的。
 
2. 提示 Client] looks like we got no XML document错误。
服务器端文件在 标签前后都不要有任何数据包括空格,空行。
 
3. Warning: SoapClient::SoapClient(): I/O warning : failed to load external entity
原因如下:PHP程序作为 SOAP客户端 采用 WSDL 模式访问远端服务器的时候,PHP是通过调用 libcurl 实现的。至少在 PHP5.2.X 是这样的。如果采用 non-WSDL 模式,就不需要 libcurl。除了 了ibcurl以外,至少还关联的库包括:libidn,ibgcc,libiconv,libintl,openssl
 
 
 
现在,你已经解决你了系统接口的问题了!剩下的空余时间,就有必要去了解什么是SOAP、http协议、XML了!
 
 
 
SoapDiscovery.class.php 文件
 
View Code
 
 
修正版:
根据YII 的CWsdlGenerator改变而来,
 
增加了接口参数的类型识别;
 
使用前需使用IDE对方法名进行注释,方可自动生成有效的WSDL文件。(具体原因可查看代码processMethod方法中的115行)
 
 
 
 
 
调用方法:
 
include(dirname(__FILE__) . './SoapDiscovery.class.php');
$disco = new SoapDiscovery();
$disco->getWSDL('service', 'http://www.xxx.com/service.php');
?>    
 
 
 
复制代码
 
/**
 * CWsdlGenerator class file.
 *
 * @author Qiang Xue
 * @link http://www.yiiframework.com/
 * @copyright Copyright © 2008-2011 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
 
/**
 * CWsdlGenerator generates the WSDL for a given service class.
 *
 * The WSDL generation is based on the doc comments found in the service class file.
 * In particular, it recognizes the '@soap' tag in the comment and extracts
 * API method and type definitions.
 *
 * In a service class, a remote invokable method must be a public method with a doc
 * comment block containing the '@soap' tag. In the doc comment, the type and name
 * of every input parameter and the type of the return value should be declared using
 * the standard phpdoc format.
 *
 * CWsdlGenerator recognizes the following primitive types (case-sensitive) in
 * the parameter and return type declarations:
 *
     *
  • str/string: maps to xsd:string;
  •  *
  • int/integer: maps to xsd:int;
  •  *
  • float/double: maps to xsd:float;
  •  *
  • bool/boolean: maps to xsd:boolean;
  •  *
  • date: maps to xsd:date;
  •  *
  • time: maps to xsd:time;
  •  *
  • datetime: maps to xsd:dateTime;
  •  *
  • array: maps to xsd:string;
  •  *
  • object: maps to xsd:struct;
  •  *
  • mixed: maps to xsd:anyType.
  •  *
     *
     * If a type is not a primitive type, it is considered as a class type, and
     * CWsdlGenerator will look for its property declarations. Only public properties
     * are considered, and they each must be associated with a doc comment block containg
     * the '@soap' tag. The doc comment block should declare the type of the property.
     *
     * CWsdlGenerator recognizes the array type with the following format:
     *
     * typeName[]: maps to tns:typeNameArray
     *
     *
     * The following is an example declaring a remote invokable method:
     *
     * / **
     *   * A foo method.
     *   * @param string name of something
     *   * @param string value of something
     *   * @return string[] some array
     *   * @soap
     *   * /
     * public function foo($name,$value) {...}
     *
     *
     * And the following is an example declaring a class with remote accessible properties:
     *
     * class Foo {
     *     / **
     *       * @var string name of foo
     *       * @soap
     *       * /
     *     public $name;
     *     / **
     *       * @var Member[] members of foo
     *       * @soap
     *       * /
     *     public $members;
     * }
     *
     * In the above, the 'members' property is an array of 'Member' objects. Since 'Member' is not
     * a primitive type, CWsdlGenerator will look further to find the definition of 'Member'.
     *
     * @author Qiang Xue
     * @version $Id: CWsdlGenerator.php 2799 2011-01-01 19:31:13Z qiang.xue $
     * @package system.web.services
     * @since 1.0
     */
    class SoapDiscovery {
     
        /**
         * @var string the namespace to be used in the generated WSDL.
         * If not set, it defaults to the name of the class that WSDL is generated upon.
         */
        public $namespace;
     
        /**
         * @var string the name of the generated WSDL.
         * If not set, it defaults to "urn:{$className}wsdl".
         */
        public $serviceName;
        private $_operations;
        private $_types;
        private $_messages;
     
        /**
         * Generates the WSDL for the given class.
         * @param string $className class name
         * @param string $serviceUrl Web service URL
         * @param string $encoding encoding of the WSDL. Defaults to 'UTF-8'.
         * @return string the generated WSDL
         */
        public function getWSDL($className, $serviceUrl, $encoding = 'UTF-8') {
            $this->_operations = array();
            $this->_types = array();
            $this->_messages = array();
            if ($this->serviceName === null)
                $this->serviceName = $className;
            if ($this->namespace === null)
                $this->namespace = "urn:{$className}wsdl";
     
            $reflection = new ReflectionClass($className);
            foreach ($reflection->getMethods() as $method) {
                if ($method->isPublic())
                    $this->processMethod($method);
            }
     
            //return $this->buildDOM($serviceUrl, $encoding)->saveXML();
     
            $fso = fopen($this->serviceName . ".wsdl", "w");
            fwrite($fso, $this->buildDOM($serviceUrl, $encoding)->saveXML());
        }
     
        /*
         * @param ReflectionMethod $method method
         */
     
        private function processMethod($method) {
            $comment = $method->getDocComment();
     
            if (strpos($comment, '@soap') === false)
                return;
            
            $methodName = $method->getName();
            $comment = preg_replace('/^\s*\**(\s*?$|\s*)/m', '', $comment);
            $params = $method->getParameters();
            $message = array();
            $n = preg_match_all('/^@param\s+([\w\.]+(\[\s*\])?)\s*?(.*)$/im', $comment, $matches);
     
            if ($n > count($params))
                $n = count($params);
            for ($i = 0; $i < $n; ++$i)
                $message[$params[$i]->getName()] = array($this->processType($matches[1][$i]), trim($matches[3][$i])); // name => type, doc
     
     
            $this->_messages[$methodName . 'Request'] = $message;
     
            if (preg_match('/^@return\s+([\w\.]+(\[\s*\])?)\s*?(.*)$/im', $comment, $matches))
                $return = array($this->processType($matches[1]), trim($matches[2])); // type, doc
            else
                $return = null;
     
            $this->_messages[$methodName . 'Response'] = array('return' => $return);
     
            if (preg_match('/^\/\*+\s*([^@]*?)\n@/s', $comment, $matches))
                $doc = trim($matches[1]);
            else
                $doc = '';
            $this->_operations[$methodName] = $doc;
        }
     
        /*
         * @param string $type PHP variable type
         */
     
        private function processType($type) {
            static $typeMap = array(
        'string' => 'xsd:string',
        'str' => 'xsd:string',
        'int' => 'xsd:int',
        'integer' => 'xsd:integer',
        'float' => 'xsd:float',
        'double' => 'xsd:float',
        'bool' => 'xsd:boolean',
        'boolean' => 'xsd:boolean',
        'date' => 'xsd:date',
        'time' => 'xsd:time',
        'datetime' => 'xsd:dateTime',
        'array' => 'soap-enc:Array',
        'object' => 'xsd:struct',
        'mixed' => 'xsd:anyType',
            );
            if (isset($typeMap[$type]))
                return $typeMap[$type];
            else if (isset($this->_types[$type]))
                return is_array($this->_types[$type]) ? 'tns:' . $type : $this->_types[$type];
            else if (($pos = strpos($type, '[]')) !== false) { // if it is an array
                $type = substr($type, 0, $pos);
                if (isset($typeMap[$type]))
                    $this->_types[$type . '[]'] = 'xsd:' . $type . 'Array';
                else {
                    $this->_types[$type . '[]'] = 'tns:' . $type . 'Array';
                    $this->processType($type);
                }
                return $this->_types[$type . '[]'];
            }
        }
     
        /*
         * @param string $serviceUrl Web service URL
         * @param string $encoding encoding of the WSDL. Defaults to 'UTF-8'.
         */
     
        private function buildDOM($serviceUrl, $encoding) {
            $xml = "
    serviceName}\" targetNamespace=\"{$this->namespace}\"
         xmlns=\"http://schemas.xmlsoap.org/wsdl/\"
         xmlns:tns=\"{$this->namespace}\"
         xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"
         xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
         xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\"
         xmlns:soap-enc=\"http://schemas.xmlsoap.org/soap/encoding/\">";
     
            $dom = new DOMDocument();
            $dom->loadXml($xml);
            $this->addTypes($dom);
     
            $this->addMessages($dom);
            $this->addPortTypes($dom);
            $this->addBindings($dom);
            $this->addService($dom, $serviceUrl);
     
            return $dom;
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         */
     
        private function addTypes($dom) {
            if ($this->_types === array())
                return;
            $types = $dom->createElement('wsdl:types');
            $schema = $dom->createElement('xsd:schema');
            $schema->setAttribute('targetNamespace', $this->namespace);
            foreach ($this->_types as $phpType => $xmlType) {
                if (is_string($xmlType) && strrpos($xmlType, 'Array') !== strlen($xmlType) - 5)
                    continue;  // simple type
                $complexType = $dom->createElement('xsd:complexType');
                if (is_string($xmlType)) {
                    if (($pos = strpos($xmlType, 'tns:')) !== false)
                        $complexType->setAttribute('name', substr($xmlType, 4));
                    else
                        $complexType->setAttribute('name', $xmlType);
                    $complexContent = $dom->createElement('xsd:complexContent');
                    $restriction = $dom->createElement('xsd:restriction');
                    $restriction->setAttribute('base', 'soap-enc:Array');
                    $attribute = $dom->createElement('xsd:attribute');
                    $attribute->setAttribute('ref', 'soap-enc:arrayType');
                    $attribute->setAttribute('wsdl:arrayType', substr($xmlType, 0, strlen($xmlType) - 5) . '[]');
                    $restriction->appendChild($attribute);
                    $complexContent->appendChild($restriction);
                    $complexType->appendChild($complexContent);
                }
                else if (is_array($xmlType)) {
                    $complexType->setAttribute('name', $phpType);
                    $all = $dom->createElement('xsd:all');
                    foreach ($xmlType as $name => $type) {
                        $element = $dom->createElement('xsd:element');
                        $element->setAttribute('name', $name);
                        $element->setAttribute('type', $type[0]);
                        $all->appendChild($element);
                    }
                    $complexType->appendChild($all);
                }
                $schema->appendChild($complexType);
                $types->appendChild($schema);
            }
     
            $dom->documentElement->appendChild($types);
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         */
     
        private function addMessages($dom) {
            foreach ($this->_messages as $name => $message) {
                $element = $dom->createElement('wsdl:message');
                $element->setAttribute('name', $name);
                foreach ($this->_messages[$name] as $partName => $part) {
                    if (is_array($part)) {
                        $partElement = $dom->createElement('wsdl:part');
                        $partElement->setAttribute('name', $partName);
                        $partElement->setAttribute('type', $part[0]);
                        $element->appendChild($partElement);
                    }
                }
                $dom->documentElement->appendChild($element);
            }
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         */
     
        private function addPortTypes($dom) {
            $portType = $dom->createElement('wsdl:portType');
            $portType->setAttribute('name', $this->serviceName . 'PortType');
            $dom->documentElement->appendChild($portType);
            foreach ($this->_operations as $name => $doc)
                $portType->appendChild($this->createPortElement($dom, $name, $doc));
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         * @param string $name method name
         * @param string $doc doc
         */
     
        private function createPortElement($dom, $name, $doc) {
            $operation = $dom->createElement('wsdl:operation');
            $operation->setAttribute('name', $name);
     
            $input = $dom->createElement('wsdl:input');
            $input->setAttribute('message', 'tns:' . $name . 'Request');
            $output = $dom->createElement('wsdl:output');
            $output->setAttribute('message', 'tns:' . $name . 'Response');
     
            $operation->appendChild($dom->createElement('wsdl:documentation', $doc));
            $operation->appendChild($input);
            $operation->appendChild($output);
     
            return $operation;
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         */
     
        private function addBindings($dom) {
            $binding = $dom->createElement('wsdl:binding');
            $binding->setAttribute('name', $this->serviceName . 'Binding');
            $binding->setAttribute('type', 'tns:' . $this->serviceName . 'PortType');
     
            $soapBinding = $dom->createElement('soap:binding');
            $soapBinding->setAttribute('style', 'rpc');
            $soapBinding->setAttribute('transport', 'http://schemas.xmlsoap.org/soap/http');
            $binding->appendChild($soapBinding);
     
            $dom->documentElement->appendChild($binding);
     
            foreach ($this->_operations as $name => $doc)
                $binding->appendChild($this->createOperationElement($dom, $name));
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         * @param string $name method name
         */
     
        private function createOperationElement($dom, $name) {
            $operation = $dom->createElement('wsdl:operation');
            $operation->setAttribute('name', $name);
            $soapOperation = $dom->createElement('soap:operation');
            $soapOperation->setAttribute('soapAction', $this->namespace . '#' . $name);
            $soapOperation->setAttribute('style', 'rpc');
     
            $input = $dom->createElement('wsdl:input');
            $output = $dom->createElement('wsdl:output');
     
            $soapBody = $dom->createElement('soap:body');
            $soapBody->setAttribute('use', 'encoded');
            $soapBody->setAttribute('namespace', $this->namespace);
            $soapBody->setAttribute('encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/');
            $input->appendChild($soapBody);
            $output->appendChild(clone $soapBody);
     
            $operation->appendChild($soapOperation);
            $operation->appendChild($input);
            $operation->appendChild($output);
     
            return $operation;
        }
     
        /*
         * @param DOMDocument $dom Represents an entire HTML or XML document; serves as the root of the document tree
         * @param string $serviceUrl Web service URL
         */
     
        private function addService($dom, $serviceUrl) {
            $service = $dom->createElement('wsdl:service');
            $service->setAttribute('name', $this->serviceName . 'Service');
     
            $port = $dom->createElement('wsdl:port');
            $port->setAttribute('name', $this->serviceName . 'Port');
            $port->setAttribute('binding', 'tns:' . $this->serviceName . 'Binding');
     
            $soapAddress = $dom->createElement('soap:address');
            $soapAddress->setAttribute('location', $serviceUrl);
            $port->appendChild($soapAddress);
            $service->appendChild($port);
            $dom->documentElement->appendChild($service);
        }
     
    }

    如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

    支付宝 微信

    有疑问联系站长,请联系QQ:QQ咨询

    转载请注明:php wsdl接口 出自老鄢博客 | 欢迎分享