sj_royd/http_service

REST和SOAP服务的HTTP服务

v1.5.0.1 2024-07-15 11:41 UTC

This package is auto-updated.

Last update: 2024-09-15 11:57:13 UTC


README

通过REST或SOAP服务进行HTTP请求的简单库。

用法

SOAP服务

<?php 
// optional Client
class Client extends \SoapClient
{
    /**
     * @var string
     */
    private $headerNs = 'http://www.w3.org/2005/08/addressing';

    /**
     * @var resource
     */
    private $context;

    public function __construct($wsdl, array $options = [])
    {
        $this->context = stream_context_create();
        $options['stream_context'] = $this->context;
        parent::__construct($wsdl, $options);
    }

    /**
     * @param   string  $action
     * @param   array   $args
     * @param   null    $options
     * @param   null    $in_heads
     * @param   null    $out_heads
     *
     * @return mixed
     */
    public function __soapCall($action, $args, $options = null, $in_heads = null, &$out_heads = null)
    {
        $in_heads = $this->getRequestHeaders($action);

        return parent::__soapCall($action, [$args], $options, $in_heads, $out_heads);
    }

    /**
     * @param   string  $request
     * @param   string  $location
     * @param   string  $action
     * @param   int     $version
     * @param   int     $one_way
     *
     * @return string
     */
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);

        return stristr(stristr($response, '<s:'), '</s:Envelope>', true) . '</s:Envelope>';;
    }

    /**
     * @param $myData
     */
    public function setMyHeader($myData)
    {
        stream_context_set_option($this->context, [
            'http' => ['header' => "my-data: {$myData}"]
        ]);
    }

    /**
     * @param $data
     *
     * @return array
     */
    private function getRequestHeaders($data)
    {
        return [
            new \SoapHeader($this->headerNs, 'Name', $data)
        ];
    }
}

class MyService extends SJRoyd\HTTPService\SoapRequest 
{
    protected $ws_path = 'https://sample.service.com';
    protected $ws_name = 'service1'; // https://sample.service.com/service1
    protected $soapVersion = SOAP_1_1; // default SOAP_1_2
    protected $wsdl = true; // default
    protected $wsdl_config = []; // SOAP WSDL options

    // optional Client injection 
    public function __construct($test = false, $debug = false) 
    {
        parent::__construct($test, $debug, Client::class);
        $this->client->__setLocation('My_Location_Data');
    }

    public function callAction()
    {
        $this->client->setMyHeader('some-data');
        $body = []; // action body params as array or an array convertible object
        $cast = [
            200   => Some\Response\Class::class,
            '4..' => Some\Response\Error::class // any 400+ status code response    
        ];
        $response = $this->call('actionName', $body, $cast);
    }
}

REST服务

<?php

class MyService extends SJRoyd\HTTPService\RestRequest
{
    protected $ws_path = 'https://sample.service.com/api';
}

class MyServiceAction extends MyService
{
    protected $ws_name = 'service1'; // https://sample.service.com/api/service1

    public function getAction()
    {
        $response = $this->callGet('getAction', [], [
            200   => Some\Response\Unit::class,
            401   => Some\Response\Error\Unauthorized::class,
            '4..' => Some\Response\Error::class // any 400+ status code response    
        ]);

        if($response instanceof \Exception){
            throw new \Exception($response->getMessage(), $this->responseStatusCode);
        }
        return $response;
    }

    public function putAction(array $data){
        $params = [ // Guzzle request params
            'json' => $data
        ];

        $cast = [
            401   => Some\Response\Error\Unauthorized::class,
            '5..' => Some\Response\Error::class // any 500+ status code response    
        ];
    
        $response = $this->callPut('putAction', $params, $cast);

        if($response instanceof \Exception){
            throw new \Exception($response->getMessage(), $this->responseStatusCode);
        }
        return true;
    }

    public function postAction(array $data){
        $params = [ // Guzzle request params
            'method' => 'POST',
            'json' => $data
        ];

        $cast = [
            200   => Some\Response\Unit::class,
            401   => Some\Response\Error\Unauthorized::class,
            '5..' => Some\Response\Error::class // any 500+ status code response    
        ];
    
        $response = $this->call('postAction', $params, $cast);

        if($response instanceof \Exception){
            throw new \Exception($response->getMessage(), $this->responseStatusCode);
        }
        return $response;
    }
}

RestRequest具有GET、POST、PUT、PATCH和DELETE请求的方法,并调用callGet()callPost()callPut()callPatch()callDelete()。您还可以使用call()方法,并在params数组中发送HTTP方法,例如$params = ['method' => 'PUT'],但默认方法是GET。

PHP 8.x命名参数

<?php

class MyService extends SJRoyd\HTTPService\RestRequest
{
    protected $ws_path = 'https://sample.service.com/api';
}

class MyServiceAction extends MyService
{
    protected $ws_name = 'service1'; // https://sample.service.com/api/service1

    public function getAction()
    {
        $response = $this->callGet( // call GET https://sample.service.com/api/service1/getAction
            action: 'getAction',
            cast: [
                200   => Some\Response\Unit::class,
                401   => Some\Response\Error\Unauthorized::class,
                '4..' => Some\Response\Error::class // any 400+ status code response    
            ]
        );

        if ($this->responseStatusCode == 200) {
            return $response;
        } else {
            throw $response;
        }
        return $response;
    }

    public function putAction(array $data)
    {    
        $response = $this->callPut( // call PUT https://sample.service.com/api/service1/putAction
            action: 'putAction',
            params: [ // Guzzle request params
                'json' => $data
            ],
            cast: [
                401   => Some\Response\Error\Unauthorized::class,
                '5..' => Some\Response\Error::class // any 500+ status code response    
            ]
        );

        if ($this->responseStatusCode == 200) {
            return true;
        } else {
            throw $response;
        }
    }

    public function postAction(array $data)
    {
        $params = [ // Guzzle request params
            'method' => 'POST',
            'json' => $data
        ];

        $cast = [
            200   => Some\Response\Unit::class,
            401   => Some\Response\Error\Unauthorized::class,
            '5..' => Some\Response\Error::class // any 500+ status code response    
        ];
    
        $response = $this->call(action: 'postAction', params: $params, cast: $cast); // call POST https://sample.service.com/api/service1/postAction

        if ($this->responseStatusCode == 200) {
            return $response;
        } else {
            throw $response;
        }
    }
    
    public function defaultAction(array data)
    {
        $response = $this->callPost( // call POST https://sample.service.com/api/service1
            cast: [
                401       => Some\Response\Error\Unauthorized::class,
                '400|404' => Some\Response\Error::class // 400 and 404 status code response    
            ]
        );

        if ($this->responseStatusCode == 200) {
            return $response; // raw data
        } else {
            throw $response;
        }
        return $response;
    }
}

获取响应原始数据

调用任何服务操作后,原始响应总是可以通过调用getRawData()方法获得。

<?php

$service->getAction(); // Some\Response\Unit instance
$service->getRawData(); // The raw data before casting to the object