voku/httpful

一个可读的、链式调用、REST友好的PHP HTTP客户端

3.0.1 2023-07-22 01:03 UTC

README

Build Status codecov.io Codacy Badge Latest Stable Version Total Downloads License Donate to this project using Paypal Donate to this project using Patreon

📯 Httpful

几年前从 nategood/httpful 分支出来,并增加了对并行请求的支持,实现了许多PSR接口:一个链式调用、REST友好的cURL包装器,实现了许多"PSR-HTTP"接口。

特性

  • 支持可读的HTTP方法(GET、PUT、POST、DELETE、HEAD、PATCH和OPTIONS)
  • 自定义头部
  • 自动“智能”解析
  • 自动负载序列化
  • 基本认证
  • 客户端证书认证(SSL)
  • 请求“下载”
  • 请求“模板”
  • 并行请求(通过curl_multi)
  • PSR-3:日志接口
  • PSR-7:HTTP消息接口
  • PSR-17:HTTP工厂接口
  • PSR-18:HTTP客户端接口

示例

<?php

// Make a request to the GitHub API.

$uri = 'https://api.github.com/users/voku';
$response = \Httpful\Client::get($uri, null, \Httpful\Mime::JSON);

echo $response->getBody()->name . ' joined GitHub on ' . date('M jS Y', strtotime($response->getBody()->created_at)) . "\n";
<?php

// Make a request to the GitHub API with a custom
// header of "X-Foo-Header: Just as a demo".

$uri = 'https://api.github.com/users/voku';
$response = \Httpful\Client::get_request($uri)->withAddedHeader('X-Foo-Header', 'Just as a demo')
                                              ->expectsJson()
                                              ->send();

$result = $response->getRawBody();

echo $result['name'] . ' joined GitHub on ' . \date('M jS Y', \strtotime($result['created_at'])) . "\n";
<?php

// BasicAuth example with MultiCurl for async requests.

/** @var \Httpful\Response[] $results */
$results = [];
$multi = new \Httpful\ClientMulti(
    static function (\Httpful\Response $response, \Httpful\Request $request) use (&$results) {
        $results[] = $response;
    }
);

$request = (new \Httpful\Request(\Httpful\Http::GET))
    ->withUriFromString('https://postman-echo.com/basic-auth')
    ->withBasicAuth('postman', 'password');

$multi->add_request($request);
// $multi->add_request(...); // add more calls here

$multi->start();

// DEBUG
//print_r($results);

安装

composer require voku/httpful

处理器

我们可以通过为特定MIME类型注册一个具有不同配置选项的解析器来覆盖默认解析器配置选项

示例:为XMLHandler解析器设置命名空间

$conf = ['namespace' => 'http://example.com'];
\Httpful\Setup::registerMimeHandler(\Httpful\Mime::XML, new \Httpful\Handlers\XmlMimeHandler($conf));

处理器是简单的类,用于解析响应体和序列化请求负载。所有处理器都必须实现MimeHandlerInterface接口,并实现两个方法:serialize($payload)parse($response)。让我们构建一个非常基本的处理器来注册为text/csv MIME类型。

<?php

class SimpleCsvMimeHandler extends \Httpful\Handlers\DefaultMimeHandler
{
    /**
     * Takes a response body, and turns it into
     * a two dimensional array.
     *
     * @param string $body
     *
     * @return array
     */
    public function parse($body)
    {
        return \str_getcsv($body);
    }

    /**
     * Takes a two dimensional array and turns it
     * into a serialized string to include as the
     * body of a request
     *
     * @param mixed $payload
     *
     * @return string
     */
    public function serialize($payload)
    {
        // init
        $serialized = '';

        foreach ($payload as $line) {
            $serialized .= '"' . \implode('","', $line) . '"' . "\n";
        }

        return $serialized;
    }
}

\Httpful\Setup::registerMimeHandler(\Httpful\Mime::CSV, new SimpleCsvMimeHandler());

最后,您必须为此MIME类型注册此处理器。

\Httpful\Setup::register(Mime::CSV, new SimpleCsvHandler());

在源代码中注册处理器之后,默认情况下,任何MIME类型为text/csv的响应都应由此处理器解析。