spapi-studio/restapi

核心提供构建API客户端的统一接口

3.1.3 2021-10-10 14:03 UTC

This package is auto-updated.

Last update: 2024-09-10 20:25:00 UTC


README

提供构建API客户端的统一接口

首先创建你的客户端类

use SapiStudio\RestApi\AbstractHttpClient;

/**
 * Class HttpClient.
 */
class HttpClient extends AbstractHttpClient
{
    protected $headers = [
          any custom header as array
    ];

    protected $requestModifiers = [RequestModifier::class];

    protected $responseFormat = 'xml json or txt';
    
    protected function buildRequestUri($baseUri,$path=false)
    {
        format your own custom request url
    }
}

然后创建你的修改器

use SapiStudio\RestApi\Request\Modifier;

class RequestModifier extends Modifier
{
    public function apply()
    {
        $this->httpClient->setOption('base_uri', $this->httpClient->getConfig('your config key set on init'));//this is a required parameter,the base uri of the api call
        $this->httpClient->addFormParameter('apikey', $this->httpClient->getConfig('apikey'));//if you set an api key in config,you can use it here
        return $this->httpClient;
    }
}

最后,创建你的API类

use SapiStudio\RestApi\AbstractApi;

class MyApi extends AbstractApi
{
    public function myapiFunction()
    {
        $this->addFormParameter('apifunc',$functionName);
        return $this->post(true,$parameters);
        return $this->get(true,$parameters);
    }
}

现在来使用它

$class      = new HttpClient();
$class->setConfig(['key'        => value]);
$apicall = $class->api('MyApi')->myapiFunction();