1of0 / curly
cURL wrapper
Requires
- php: ^7.2
- ext-curl: *
- ext-json: *
- 1of0/streams: ^0.1.3
- laminas/laminas-diactoros: ^1.0|^2.0
- psr/http-message: ^1.0
Requires (Dev)
- phpunit/phpunit: ^8.0
- roave/security-advisories: dev-master
Suggests
- ext-mbstring: *
README
Curly
Curly is an object oriented wrapper around PHP's cURL extension.
Basic usage
To execute requests you may provide a URL and HTTP method, but you may also provide an instance of PSR-7's
RequestInterface as a base to configure the cURL channel.
<?php
use OneOfZero\Curly\Curly;
$curly = new Curly();
// Using PSR-7 RequestInterface implementation
$request = (new Laminas\Diactoros\Request)
->withMethod('POST')
->withUri(new Laminas\Diactoros\Uri('https://example.com'))
->withHeader('Accepts', 'application/json');
$response = $curly->request($request);
// Using plain URL and method
$response = $curly->requestByUrl('https://example.com', 'DELETE');
// Using ExtendedServerRequest
$request = (new \OneOfZero\Curly\ExtendedServerRequest)
->withUriString('https://example.com', 'resource', '1337')
->withMethod('POST')
->withUrlEncodedForm(['foo' => 'bar'])
->withHeader('Accepts', 'application/json');
$response = $curly->request($request);
By default, the requestByUrl() and request() methods will return a ResponseInterface. To process the response
manually, you may configure callbacks or configure a custom handler (which under water will configure callbacks, but
provides a cleaner programming interface).
Custom configuration
cURL options
The options that would normally be set through curl_setopt must be set through a CurlyOptions instance. The
CurlyOptions instance can be reused over multiple requests.
Custom handlers
Instead of manually configuring callbacks in the CurlyOptions object, you may extend the AbstractHandler class to
hook into events. The library comes with two implementations of the AbstractHandler. The CancellableHandler and
StreamHandler.
The CancellableHandler is provided a callback during instantiation. During the transfer, cURL's progress event is
routed to the handler, which in turn invokes the callback to determine whether the transfer should be aborted.
The StreamHandler decorates the CancellableHandler and is an example of a handler that hooks into cURL's read and
write callbacks. It probably isn't very useful since setting the inputStream and outputStream options in the
CurlyOptions object would achieve more or less the same, but helps demonstrate the usage of the callbacks.
The power of the streams is that it allows you to read/write downloads and uploads in chunks. Combined with streams you can prevent memory exhaustion when handling large amounts of data.