masnathan / api-caller
此包已被废弃,不再维护。未建议替代包。
调用API变得简单。
v2.0.0
2017-07-21 10:14 UTC
Requires
- php: >=5.6
- masnathan/parser: ^0.0.1
- php-http/client-common: ^1.2
- php-http/client-implementation: ^1.0
- php-http/discovery: ^1.0
Requires (Dev)
- guzzlehttp/psr7: ^1.0
- php-http/curl-client: ^1.6
- php-http/mock-client: ^1.0.1
- symfony/var-dumper: ^3.1
README
APIcaller是一个帮助你构建API包装器的类。
你不必担心构建URL,甚至不必担心解析请求数据。
如何使用
你需要扩展Client
类和Caller
类,其中Client
将处理所有请求配置,而Caller
将用作与API交互的接口。
use MASNathan\APICaller\Client; use MASNathan\APICaller\Caller; class MyPackageClient extends Client { /** * Here you can set the default headers and parameters on a global scope */ public function __construct($ip = null) { $this->setDefaultHeaders([ 'User-Agent' => 'PHP APICaller SDK', 'Accept' => 'application/json', 'Token' => '123456', ]); $this->setDefaultParameters([ 'ip' => $ip ?: '127.0.0.1', ]); } /** * Returns the API Endpoint * * @return string */ public function getEndpoint() { return 'http://api.domain.com/v1/'; } } class MyPackageCaller extends Caller { public function requestSomething($foo, $bar) { $params = [ 'foo' => $foo, 'bar' => $bar, ]; // this will result in this url http://api.domain.com/v1/some-method.json?ip={$ip}&foo={$foo}&bar={$bar} $response = $this->client->get('some-method.json', $params); $data = $this->handleResponseContent($response, 'json'); // Do something with your data return $data; } }
好了,这就是你开始创建你的类的方法,现在让我们做一些调用吧!
$client = new MyPackageClient('8.8.8.8'); $caller = new MyPackageCaller($client); $result = $caller->requestSomething(13, 37); var_dump($result);
这将调用以下URL:http://api.domain.com/v1/some-method.json?ip=8.8.8.8&foo=13&bar=37
。
安装
要安装SDK,你需要在项目中使用Composer。如果你没有安装Composer,请检查此页面并按照安装步骤进行操作
此库并非严格耦合到Guzzle或其他发送HTTP消息的库。它使用了一个名为HTTPlug的抽象。这将给你提供选择要使用的PSR-7实现和HTTP客户端的灵活性。
要尽快开始,你应该运行以下命令
# Add APIcaller as a dependency
$ composer require masnathan/api-caller php-http/curl-client guzzlehttp/psr7
为什么我需要要求所有这些包?
APICaller依赖于虚拟包php-http/client-implementation,它要求你安装一个适配器,但我们并不关心是哪一个。这是应用程序中的实现细节。我们还需要一个PSR-7实现和一个消息工厂。
如果你不想要,不必使用php-http/curl-client。更多关于虚拟包的信息,为什么这是一个好主意以及它带来的灵活性,请参阅HTTPlug文档。
许可证
此库受MIT许可证的约束,完整的许可证请见此处