Sink - matical/nana GitHub Wiki

Note for Laravel

If you're using Laravel, you should skip this part and checkout ksmz/nana-laravel instead. It allows you to pre-configure sinks in your config as well as make use of existing filesystems (in Laravel).

Sinks

Sinks are partly inspired by how Laravel handles filesystems. They can hold multiple pre-configured faucets (Guzzle clients). You may have different configurations that you want to reuse throughout your code.

use ksmz\nana\Sink;

Sink::registerFaucet($name, array $config);

$config is passed directly to the underlying Guzzle instance, so refer to their documentation.

Though you keep in mind options that clashes with the entire request should be avoided.

  • body/form_params/multipart/json
  • sink
  • etc.

Registering Faucets

Faucets are lazy-loaded. A new Fetch is only instantiated (and cached) on the first call to any of the methods.

$options = [
    'base_uri'    => 'https://httpbin.org',
    'http_errors' => false,
];

Sink::register('default', $options);

You can then call any of the methods on Fetch like you normally would.

Sink::faucet('default')->get('/get');

Since the faucet is marked as default, you can omit the call to faucet() and call Fetch methods directly on the Sink.

Sink::userAgent('CustomAgent/0.1')->get('/get');

Change default sink

If you like, you can use something else besides "default".

// Implicit calls will be forwarded to 'my-default-sink'.
Sink::setDefaultSink('my-default-sink');

// Functionally the same calls
Sink::get('/get');
Sink::faucet('my-default-sink')->get('/get');

Examples

Note: You can still configure clients "fluently" after retrieving them from the sink.

Sink::register('images', [
    'base_uri' => 'https://custom-api-endpoint',
    'headers'  => [
        'User-Agent'    => 'CustomAgent/0.1',
        'Accept'        => 'application/x.kaede.v2+json',
        'Authorization' => 'Bearer ' . env('API_SECRET'),
    ],
]);

Sink::faucet('images')
    ->withHeaders(['addtional-headers' => 'to-merge'])
    ->saveTo('/path/to/image.png')
    ->get('/image');