项目作者: chillerlan

项目描述 :
A http client wrapper/PSR-7/PSR-15/PSR-17/PSR-18 implementation for PHP 7.4+.
高级语言: PHP
项目地址: git://github.com/chillerlan/php-httpinterface.git
创建时间: 2018-01-23T09:36:29Z
项目社区:https://github.com/chillerlan/php-httpinterface

开源协议:MIT License

下载


chillerlan/php-httpinterface

A PSR-7/PSR-17/PSR-18 HTTP message/client implementation.

PHP Version Support
version
license
Continuous Integration
Coverage
Codacy
Packagist downloads

Documentation

An API documentation created with phpDocumentor can be found at https://chillerlan.github.io/php-httpinterface/ (WIP).

Requirements

Installation with composer

Terminal

  1. composer require chillerlan/php-httpinterface

composer.json

  1. {
  2. "require": {
  3. "php": "^8.1",
  4. "chillerlan/php-httpinterface": "dev-main#<commit_hash>"
  5. }
  6. }

Note: replace dev-main with a version constraint, e.g. ^6.0 - see releases for valid versions.

Profit!

Quickstart

The HTTP clients CurlClient and StreamClient are invoked with a ResponseFactoryInterface instance
as the first parameter, followed by optional HTTPOptions and PSR-3 LoggerInterface instances.
You can then send a request via the implemented PSR-18 method ClientInterface::sendRequest(),
using a PSR-7 RequestInterface and expect a PSR-7 ResponseInterface.

CurlClient, StreamClient

  1. $options = new HTTPOptions;
  2. $options->ca_info = '/path/to/cacert.pem';
  3. $options->user_agent = 'my cool user agent 1.0';
  4. $options->dns_over_https = 'https://cloudflare-dns.com/dns-query';
  5. $httpClient = new CurlClient($responseFactory, $options, $logger);
  6. $request = $requestFactory->createRequest('GET', 'https://www.example.com?foo=bar');
  7. $httpClient->sendRequest($request);

CurlMultiClient

The CurlMultiClient client implements asynchronous multi requests (“rolling-curl”).
It needs a MultiResponseHandlerInterface that parses the incoming responses, the callback may return a failed request to the stack:

  1. $handler = new class () implements MultiResponseHandlerInterface{
  2. public function handleResponse(
  3. ResponseInterface $response, // the incoming response
  4. RequestInterface $request, // the corresponding request
  5. int $id, // the request id
  6. array|null $curl_info, // the curl_getinfo() result for this request
  7. ):RequestInterface|null{
  8. if($response->getStatusCode() !== 200){
  9. // return the failed request back to the stack
  10. return $request;
  11. }
  12. try{
  13. $body = $response->getBody();
  14. // the response body is empty for some reason, we pretend that's fine and exit
  15. if($body->getSize() === 0){
  16. return null;
  17. }
  18. // parse the response body, store the result etc.
  19. $data = $body->getContents();
  20. // save data to file, database or whatever...
  21. // ...
  22. }
  23. catch(Throwable){
  24. // something went wrong, return the request to the stack for another try
  25. return $request;
  26. }
  27. // everything ok, nothing to return
  28. return null;
  29. }
  30. };

You can then invoke the multi request client - the MultiResponseHandlerInterface and ResponseFactoryInterface are mandatory,
HTTPOptions and LoggerInterface are optional:

  1. $options = new HTTPOptions;
  2. $options->ca_info = '/path/to/cacert.pem';
  3. $options->user_agent = 'my cool user agent 1.0';
  4. $options->sleep = 750000; // microseconds, see usleep()
  5. $options->window_size = 5;
  6. $options->retries = 1;
  7. $multiClient = new CurlMultiClient($handler, $responseFactory, $options, $logger);
  8. // create and add the requests
  9. foreach(['..', '...', '....'] as $item){
  10. $multiClient->addRequest($factory->createRequest('GET', $endpoint.'/'.$item));
  11. }
  12. // process the queue
  13. $multiClient->process();

URLExtractor

The URLExtractor wraps a PSR-18 ClientInterface to extract and follow shortened URLs to their original location.

  1. $options = new HTTPOptions;
  2. $options->user_agent = 'my cool user agent 1.0';
  3. $options->ssl_verifypeer = false;
  4. $options->curl_options = [
  5. CURLOPT_FOLLOWLOCATION => false,
  6. CURLOPT_MAXREDIRS => 25,
  7. ];
  8. $httpClient = new CurlClient($responseFactory, $options, $logger);
  9. $urlExtractor = new URLExtractor($httpClient, $responseFactory);
  10. $request = $factory->createRequest('GET', 'https://t.co/ZSS6nVOcVp');
  11. $urlExtractor->sendRequest($request); // -> response from the final location
  12. // you can retrieve an array with all followed locations afterwards
  13. $responses = $this->http->getResponses(); // -> ResponseInterface[]
  14. // if you just want the URL of the final location, you can use the extract method:
  15. $url = $this->http->extract('https://t.co/ZSS6nVOcVp'); // -> https://api.guildwars2.com/v2/build

LoggingClient

The LoggingClient wraps a ClientInterface and outputs the HTTP messages in a readable way through a LoggerInterface (do NOT use in production!).

  1. $loggingClient = new LoggingClient($httpClient, $logger);
  2. $loggingClient->sendRequest($request); // -> log to output given via logger

Auto generated API documentation

The API documentation can be auto generated with phpDocumentor.
There is an online version available via the gh-pages branch that is automatically deployed on each push to main.

Locally created docs will appear in the directory .build/phpdocs/. If you’d like to create local docs, please follow these steps:

  • download phpDocumentor v3+ as .phar archive
  • run it in the repository root directory:
    • on Windows c:\path\to\php.exe c:\path\to\phpDocumentor.phar --config=phpdoc.xml
    • on Linux just php /path/to/phpDocumentor.phar --config=phpdoc.xml
  • open index.html in a browser
  • profit!

Disclaimer

Use at your own risk!