phanxipang / fansipan

A simple package that allows you to write your API integrations or SDKs in a elegant way.
https://phanxipang.github.io/fansipan
MIT License
81 stars 2 forks source link

Connector configurator #12

Closed jenky closed 1 year ago

jenky commented 1 year ago

Description

Better way to add options for one-off request without modifying middleware globally.

Motivation and context

The decorator approach, such as RetryableConnector and FollowRedirectsConnector, has a limitation in that it cannot use methods other than those defined in the ConnectorInterface.

use Jenky\Atlas\Contracts\ConnectorInterface;
use Jenky\Atlas\Response;

interface MyConnectorInterface extends ConnectorInterface
{
    public function register(string $username, string $password): Response;
}

class MyConnector implements MyConnectorInterface
{
    public function register(string $username, string $password): Response
    {
        //....
    }
}
$connector = new RetryableConnector(new MyConnector());

// This won't work because RetryableConnector doesn't have `register` method
$response = $connector->register('foo', 'secret'); 

The ConnectorConfigurator solves this problem by dynamically modifying a connector with the desired behavior at runtime, and also allowing the IDE to suggest all the methods defined in the MyConnectorInterface.

$connector = (new ConnectorConfigurator())
    ->retry()
    ->configure(new MyConnector());

$response = $connector->register('foo', 'secret');