camoo / curl-http-client

简单的Curl Http客户端

1.1.3 2023-06-24 16:15 UTC

This package is auto-updated.

Last update: 2024-09-24 19:27:07 UTC


README

使用代码整洁架构方法构建的简单的Curl Http客户端。PSR-7标准

Build Status camoo-badge

使用方法

无依赖注入

use Camoo\Http\Curl\Infrastructure\Client;
use Camoo\Http\Curl\Domain\Entity\Configuration;

$configuration = Configuration::create();

// activate debug
// $configuration->setDebug(true);
$client = new Client($configuration);

$uri = 'https://api.example.com/v1/users';

$response = $client->get($uri);

$status = $response->getStatusCode();
$body = (string)$response->getBody();

// get all headers
$headers = $response->getHeaders();

// get single header
$header = $response->getHeader('foo');

// get status code
$code = $response->getStatusCode();

有依赖注入

## in Module
use Camoo\Http\Curl\Domain\Client\ClientInterface;
use Camoo\Http\Curl\Infrastructure\Client;

$this->bind(ClientInterface::class)->to(Client::class);

## in Adapter port

final class TemplateRepository implements TemplateRepositoryInterface
{
    private const URI = 'https://api.example.com/v2/template';
    private const SUCCESS_STATUS = 201;
    
    public function __construct(private readonly ClientInterface $client)
    {
    }
    
    public function save(Template $template): bool
    {
        $response = $this->client->post(self::URI, $template->toArray());
        return $response->getStatusCode() === self::SUCCESS_STATUS;
    }
    
    public function getById(string $id): Template
    {
        $uri = self::URI. '?id=' . $id;
        $response = $this->client->get($uri);
        if ($response->getStatusCode() !== self::SUCCESS_STATUS){
            throw new NotFoundTemplate(sprintf('Template with id %s not found!', $id));
        }
        $body = (string)$response->getBody();
        return Template::fromArray(json_decode($body, true));
    }
    # ...
}