atog / simple-api-client
基于 cUrl 的简单 API 客户端
v1.2.0
2016-05-16 11:02 UTC
Requires
- php: >=5.5
- illuminate/support: 5.1.*|5.2.*
- jyggen/curl: 4.0.x-dev
- symfony/console: ^3.0
Requires (Dev)
- phpunit/phpunit: 4.*
- squizlabs/php_codesniffer: ~2.3
This package is not auto-updated.
Last update: 2024-09-20 22:07:51 UTC
README
simple-api-client 库提供了一种简单的方式来构建公共 REST API 的包装器。
安装
通过 Composer
$ composer require atog/simple-api-client
使用方法
类
客户端
Client
类包含有关 API 的基本信息,例如 $domain
。它必须扩展抽象类 Atog\Api\Client
class Client extends \Atog\Api\Client { protected $domain = 'http://example.com/api/v1'; }
端点
端点提供查询 API 资源的功能。
class TestEndpoint extends \Atog\Api\Endpoint { protected $endpoint = 'foo'; public function find($slug) { // https://example.com/api/v1/foo/$slug gets called $this->respond( $this->client->get($this->getEndpointUrl($slug, true)) ); } }
模型
模型是资源的数据结构。可以使用 get 和 set 修改器轻松更改属性 (类似于 Laravel 的 Eloquent 修改器:https://laravel.net.cn/docs/5.2/eloquent-mutators)
class TestModel extends Model { public function getNameAttribute($value) { return strtoupper($value); } public function setFirstNameAttribute($value) { $this->attributes['first_name'] = strtolower($value); } public function setContactsAttribute($value) { $this->attributes['contacts'] = $this->makeCollection($value, Contacts::class); } }
初始化
第一个参数定义了您使用的所有端点。第二个参数提供了有关模型或 cUrl 的某些选项。在模型配置中,我们可以将模型绑定到端点
// new Client(array $endpoints, array $config = []) $client = new Client( [ TestEndpoint::class ], [ 'models' => [ 'TestEndpoint' => TestModel::class ], 'curl' => [ CURLOPT_TIMEOUT => 60 ] ] ); $foo = $client->testEndpoint->find(1); // GET http://example.com/api/v1/foo/1
变更日志
1.1.0
- 增加了对查询参数的支持
- 增加了返回 API 响应的辅助方法
1.0.0
- 初始发布
测试
$ composer test
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。