Saber

July 1, 2018 ยท View on GitHub

Latest Version Build Status Php Version Swoole Version Saber License

Intro

The PHP high-performance HTTP client for Swoole Humanized Component Library, based on Swoole native coroutine client, supports multiple styles of operation, provides high-performance solutions at the bottom, allows developers to focus on feature development, and emancipate from traditional synchronous blocking network libs.

  • Development based on Swoole Coroutine Client
  • User-friendly style, ajax.js/axios.js/requests.py users' gospel, also supports PSR style operation
  • Complete browser-level cookie management mechanism, perfect for crawler/API proxy applications
  • Request/response interceptors
  • Multiple requests concurrent, concurrent redirection optimization, automated multiplexing long connections
  • Automatic transcoding of response messages
  • HTTPS connection, CA certificate automation support
  • HTTP/Socks5 Proxy Support
  • Redirection control, automated long connection multiplexing
  • Automation Encode Request/Parse Response Data
  • Milliseconds timeout timer
  • Random UA Generator

Requirement

  • PHP71 or later
  • Swoole 2.1.2 or later
  • Swoole 4 is the best

Examples

All of Saber's static methods have a corresponding method in the instance. The static method is implemented by a default client instance.

Coroutine

Swoole implements coroutine scheduling at the bottom layer, and the business layer does not need to be aware of it. It needs to be used in event callback functions such as onRequet, onReceive, and onConnect, or wrapped using the go keyword (swoole.use_shortname is enabled by default).

go(function () {
    echo SaberGM::get('http://httpbin.org/get');
})

Easy Request

SaberGM::get('http://httpbin.org/get');
SaberGM::post('http://httpbin.org/post');
SaberGM::put('http://httpbin.org/put');
SaberGM::patch('http://httpbin.org/patch');
SaberGM::delete('http://httpbin.org/delete');

Create Instance

API proxy service applicable

$saber = Saber::create([
    'base_uri' => 'http://httpbin.org',
    'headers' => [
        'User-Agent' => null,
        'Accept-Language' => 'en,zh-CN;q=0.9,zh;q=0.8',
        'DNT' => '1'
    ],
]);
echo $saber->get('/get');
echo $saber->post('/post');
echo $saber->patch('/patch');
echo $saber->put('/put');
echo $saber->delete('/delete');

Create Session

Session instance will save cookies automatically, Its implementation is browser-level complete.

$session = Saber::session([
    'base_uri' => 'http://httpbin.org',
    'redirect' => 0
]);
$session->get('/cookies/set?foo=bar&k=v&apple=banana');
$session->get('/cookies/delete?k');
echo $session->get('/cookies')->body;

Multi Request

Note: A concurrent redirection optimization scheme is used here. Multiple redirects are always concurrent and do not degenerate into a single request for the queue.

$responses = SaberGM::requests([
    ['uri' => 'http://github.com/'],
    ['uri' => 'http://github.com/'],
    ['uri' => 'https://github.com/']
]);
echo "multi-requests [ {$responses->success_num} ok, {$responses->error_num} error ]:\n" ."consuming-time: {$responses->time}s\n";

// multi-requests [ 3 ok, 0 error ]:
// consuming-time: 0.79090881347656s
// Arguments alias make it easier.
$saber = Saber::create(['base_uri' => 'http://httpbin.org']);
echo $saber->requests([
    ['get','/get'],
    ['post','/post'],
    ['patch','/patch'],
    ['put','/put'],
    ['delete','/delete']
]);

HTTP Proxy

Support HTTP and Socks5

$uri = 'http://myip.ipip.net/';
echo SaberGM::get($uri, ['proxy' => 'http://127.0.0.1:1087'])->body;
echo SaberGM::get($uri, ['proxy' => 'socks5://127.0.0.1:1086'])->body;

PSR Style

$response = SaberGM::psr()
    ->withMethod('POST')
    ->withUri(new Uri('http://httpbin.org/post?foo=bar'))
    ->withQueryParams(['foo' => 'option is higher-level than uri'])
    ->withHeader('content-type', ContentType::JSON)
    ->withBody(new BufferStream(json_encode(['foo' => 'bar'])))
    ->exec()->recv();

echo $response->getBody();

Install

The recommended way to install Saber is through Composer

composer require swlib/saber:dev-master

how to install composer?

# Install Composer
curl -sS https://getcomposer.org/installer | php
# Global install
mv composer.phar /usr/local/bin/composer

After installing, you need to require Composer's autoloader:

require 'vendor/autoload.php';

You can then later update Saber using composer:

composer update

Configuration parameter table

| splitting multiple selectable values

keytypeintroductionexampleremark
protocol_versionstring1.1HTTP2 in the roadmap
base_uristringhttp://httpbin.orgWill merge with uri according to rfc3986
uristringhttp://httpbin.org/get | /get | getU can use absolute and relative paths
methodstringget | post | head | patch | put | deleteThe underlying layer is automatically converted to uppercase
headersarray['DNT' => '1'] | ['accept' => ['text/html'], ['application/xml']]The field names are case-insensitive, but the original case rules at the time of setting are retained. Each underlying field value is automatically split into arrays according to PSR-7.
cookiesarray|string['foo '=> 'bar'] | 'foo=bar; foz=baz'The underlying is automatically converted to a Cookies object and its domain is set to the current uri, with browser-level complete properties.
useragentstringThe default is macos platform chrome
redirectintmax-value5The default is 3, 0 is not redirected.
keep_alivebooltrue | falseThe default is true, the connection will be reused automatically when redirecting
content_typestringtext/plain | Swlib\Http\ContentType::JSONdefault is application/x-www-form-urlencoded
dataarray | string'foo=bar&dog=cat' | ['foo' => 'bar']Will automatically encode data based on content_type
beforecallable | arrayinterceptor before requestfunction(Request $request){}Specific reference to the interceptor section
aftercallable | arrayinterceptor after responsefunction(Response $response){}Ditto.
timeoutfloat0.5Default 5s, support millisecond timeout
proxystringhttp://127.0.0.1:1087 | socks5://127.0.0.1:1087suport http and socks5
sslintenable ssl?0=disable 1=enable 2=autoauto default
cafilestringca file__DIR__ . '/cacert.pem'
ssl_verify_peerboolVerify server certificatefalse | trueclose default
ssl_allow_self_signedboolAllow self-signed certificatestrue | falseallow default

Alias

keyalias
method0
uri1 | url
data2 | body
base_uribase_url
aftercallback
content_typecontent-type
cookiescookie
headersheader
redirectfollow
form_dataquery
useragentua