TP5.1创建webservice

4 篇文章 0 订阅
4 篇文章 0 订阅

TP5.1开启webservice

 

第一步:开启soap扩展

php.ini 文件里面 找到 extension=soap 把前面的分号注释

第二步:编写文件

注:所有文件都放到public目录下
1.server.php

<?php

if(file_exists('ThirdOrder.wsdl')){

    include("ThirdOrder.php");

    $objSoapServer = new SoapServer("ThirdOrder.wsdl");//ThirdOrder.wsdl是刚创建的wsdl文件

    //$objSoapServer = new SoapServer("server.php?wsdl");//这样也行

    $objSoapServer->setClass("ThirdOrder");//注册ThirdOrder类的所有方法

    $objSoapServer->handle();//处理请求

}else{

    include("ThirdOrder.php");

    include("SoapDiscovery.class.php");

    $disc = new SoapDiscovery('ThirdOrder', 'ThirdOrder');//api类文件名,service接口目录

    $res = $disc->getWSDL();

}

2.SoapDiscovery.class.php

链接: https://pan.baidu.com/s/1e8ttN2Bs8DKLCX-hIPRRaQ 提取码: i58j

<?php

class SoapDiscovery {

private $class_name = '';

private $service_name = '';

 

/**

* SoapDiscovery::__construct() SoapDiscovery class Constructor.

*

* @param string $class_name

* @param string $service_name

**/

public function __construct($class_name = '', $service_name = '') {

$this->class_name = $class_name;

$this->service_name = $service_name;

}

 

/**

* SoapDiscovery::getWSDL() Returns the WSDL of a class if the class is instantiable.

*

* @return string

**/

public function getWSDL() {

if (empty($this->service_name)) {

throw new Exception('No service name.');

}

$headerWSDL = "<?xml version=\"1.0\" ?>\n";

$headerWSDL.= "<definitions name=\"$this->service_name\" targetNamespace=\"urn:$this->service_name\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"urn:$this->service_name\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\">\n";

$headerWSDL.= "<types xmlns=\"http://schemas.xmlsoap.org/wsdl/\" />\n";

 

if (empty($this->class_name)) {

throw new Exception('No class name.');

}

 

$class = new ReflectionClass($this->class_name);

 

if (!$class->isInstantiable()) {

throw new Exception('Class is not instantiable.');

}

 

$methods = $class->getMethods();

 

$portTypeWSDL = '<portType name="'.$this->service_name.'Port">';

$bindingWSDL = '<binding name="'.$this->service_name.'Binding" type="tns:'.$this->service_name."Port\">\n<soap:binding style=\"rpc\" transport=\"http://schemas.xmlsoap.org/soap/http\" />\n";

$serviceWSDL = '<service name="'.$this->service_name."\">\n<documentation />\n<port name=\"".$this->service_name.'Port" binding="tns:'.$this->service_name."Binding\"><soap:address location=\"http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF']."\" />\n</port>\n</service>\n";

$messageWSDL = '';

foreach ($methods as $method) {

if ($method->isPublic() && !$method->isConstructor()) {

$portTypeWSDL.= '<operation name="'.$method->getName()."\">\n".'<input message="tns:'.$method->getName()."Request\" />\n<output message=\"tns:".$method->getName()."Response\" />\n</operation>\n";

$bindingWSDL.= '<operation name="'.$method->getName()."\">\n".'<soap:operation soapAction="urn:'.$this->service_name.'#'.$this->class_name.'#'.$method->getName()."\" />\n<input><soap:body use=\"encoded\" namespace=\"urn:$this->service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n</input>\n<output>\n<soap:body use=\"encoded\" namespace=\"urn:$this->service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n</output>\n</operation>\n";

    $messageWSDL.= '<message name="'.$method->getName()."Request\">\n";

$parameters = $method->getParameters();

foreach ($parameters as $parameter) {

$messageWSDL.= '<part name="'.$parameter->getName()."\" type=\"xsd:string\" />\n";

}

$messageWSDL.= "</message>\n";

$messageWSDL.= '<message name="'.$method->getName()."Response\">\n";

$messageWSDL.= '<part name="'.$method->getName()."\" type=\"xsd:string\" />\n";

$messageWSDL.= "</message>\n";

}

}

$portTypeWSDL.= "</portType>\n";

$bindingWSDL.= "</binding>\n";

$fso = fopen($this->class_name . ".wsdl" , "w");

fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>'));

fclose($fso);

}

 

/**

* SoapDiscovery::getDiscovery() Returns discovery of WSDL.

*

* @return string

**/

public function getDiscovery() {

return "<?xml version=\"1.0\" ?>\n<disco:discovery xmlns:disco=\"http://schemas.xmlsoap.org/disco/\" xmlns:scl=\"http://schemas.xmlsoap.org/disco/scl/\">\n<scl:contractRef ref=\"http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['PHP_SELF']."?wsdl\" />\n</disco:discovery>";

}

}

 

?>

3.自己的接口类
注:因为写在public下面的文件没有命名空间,所以只能按照TP的入口文件模式来书写,头部载入后,在下面引用app下面的实际业务逻辑类,所有的Db等操作都在里面完成。
runWeb()这个方法是自己根据TP的底层run()方法仿写的,将在后面贴出。

ThirdOrder.php:

 

<?php

// 加载基础文件

require __DIR__ . '/../thinkphp/base.php';

 

// 支持事先使用静态方法设置Request对象和Config对象

 

// 执行应用并响应

\think\Container::get('app')->runWeb();

 

use app\api\controller\Order;//这个路径是控制的路径

 

class ThirdOrder

{

    protected $order;

    public function __construct()

    {

        $this->order = new Order();

 

    }

 

    public function savepubInf($data){

        $res = $this->order->savepubInf($data);

        return $res;

    }

}

4.runWeb()方法
路径是 thinkphp/library/think/App.php

 

public function runWeb()

    {

        try {

            // 初始化应用

            $this->initialize();

 

            // 监听app_init

            $this->hook->listen('app_init');

 

            /*if ($this->bindModule) {

                // 模块/控制器绑定

                $this->route->bind($this->bindModule);

            } elseif ($this->config('app.auto_bind_module')) {

                // 入口自动绑定

                $name = pathinfo($this->request->baseFile(), PATHINFO_FILENAME);

                if ($name && 'index' != $name && is_dir($this->appPath . $name)) {

                    $this->route->bind($name);

                }

            }*/

 

            // 监听app_dispatch

            $this->hook->listen('app_dispatch');

 

            $dispatch = $this->dispatch;

 

            if (empty($dispatch)) {

                // 路由检测

                $dispatch = $this->routeCheck()->init();

            }

 

            // 记录当前调度信息

            $this->request->dispatch($dispatch);

 

            // 记录路由和请求信息

            if ($this->appDebug) {

                $this->log('[ ROUTE ] ' . var_export($this->request->routeInfo(), true));

                $this->log('[ HEADER ] ' . var_export($this->request->header(), true));

                $this->log('[ PARAM ] ' . var_export($this->request->param(), true));

            }

 

            // 监听app_begin

            $this->hook->listen('app_begin');

 

            // 请求缓存检查

            $this->checkRequestCache(

                $this->config('request_cache'),

                $this->config('request_cache_expire'),

                $this->config('request_cache_except')

            );

 

            $data = null;

        } catch (HttpResponseException $exception) {

            $dispatch = null;

            $data     = $exception->getResponse();

        }

 

        $this->middleware->add(function (Request $request, $next) use ($dispatch, $data) {

            return is_null($data) ? $dispatch->run() : $data;

        });

 

        $response = $this->middleware->dispatch($this->request);

 

        // 监听app_end

        $this->hook->listen('app_end', $response);

 

        return $response;

    }

第三步:启动webservice

1.运行server.php文件,会生成相应的wsdl文件,里面注册了所有你接口类的方法

 

 

生成文件后可以编写一个client.php文件来验证webservice是否启动成功
client.php

 

 

<?php

    $client = new SoapClient("http://oms.test:80/Server.php?wsdl");

    try{

        $data = [

            "orderid"=>"75879852533122871",

            "dictid"=>"3",

            "o2oCode"=>"709",

            "type"=>"1"

        ];

        $result = $client->savepubInf(json_encode($data)); // will cause a Soap Fault if divide by zero

        print "The answer is: $result";

    }catch(SoapFault $e){

        print "Sorry an error was caught executing your request: {$e->getMessage()}";

    }

 


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值