thlib / php-curl-client
一个简单且轻量级的 PHP cURL 辅助工具
1.0.0
2020-04-10 18:22 UTC
Requires
- php: >=5.3.0
- psr/http-message: ^1.0
- slim/psr7: ^1.0
- thlib/php-constants: ^1.0
- thlib/php-curl-multi-basic: ^1.0
- thlib/php-url: ^1.0
This package is auto-updated.
Last update: 2024-09-18 21:21:39 UTC
README
解决的问题
- Guzzle 很庞大且复杂。
- 随着功能的增加,文件对每个人来说都变得更大。
解决方案
- 自定义 cURL 抽象。
- 类不会增长,而是为每个新功能添加新类。
遵循 PSR-7
示例用法
<?php require 'vendor/autoload.php'; header('Content-Type: text/plain;charset=utf-8'); use TH\HttpConstants\ContentType; use TH\HttpConstants\HttpRequestHeader; use TH\CurlClient\CurlMulti; use TH\CurlClient\CurlClient; use TH\CurlClient\CurlResponse; use TH\CurlClient\Request\Authorization; use TH\CurlClient\Request\Headers; use TH\CurlClient\Request\Json; use TH\CurlClient\Request\QueryParams; // Sync request echo 'Sync request'.PHP_EOL; echo '================================='.PHP_EOL; $response = CurlClient::post('https://example.com') ->with(new Json(['key'=>'value'])) ->with(new QueryParams(['test' => 1])) ->with(new Authorization('Bearer: abc')) ->with(new Headers(['X-Test: test'])) ->send(); $status = $response->getStatusCode(); $body = $response->getBody()->__toString(); echo 'StatusCode: '.$status.PHP_EOL; foreach($response->getHeaders() as $name => $headers) { foreach($headers as $value){ echo $name.': '.$value.PHP_EOL; } } echo PHP_EOL.$body.PHP_EOL; // Async request echo PHP_EOL; echo PHP_EOL; echo 'Async request'.PHP_EOL; echo '================================='.PHP_EOL; $request = CurlClient::get('https://google.com') ->with(new Json(['key'=>'value'])) ->with(new QueryParams(['test' => 1])) ->with(new Authorization('Bearer: abc')); $multi = new CurlMulti; $multi = $multi->add($request, function(CurlResponse $response){ $status = $response->getStatusCode(); $body = $response->getBody()->__toString(); echo 'StatusCode: '.$status.PHP_EOL; foreach($response->getHeaders() as $name => $headers) { foreach($headers as $value){ echo $name.': '.$value.PHP_EOL; } } echo PHP_EOL.$body.PHP_EOL; }); $multi->send(); // Use built-in helper functions $response = CurlClient::post('https://example.com') ->withJson(['key'=>'value']) ->withQueryParams(['test' => 1]); // Call it as an instance $client = new CurlClient; $request = $client->post('https://example.com'); $request = $request->with(new Authorization('Bearer: abc')); /** @var CurlResponse $response PSR-7 Response with extra methods that are specific to curl */ $response = $request->send();
运行测试
vendor/phpunit/phpunit/phpunit --bootstrap vendor/autoload.php tests