Class ClientFactory
The factory to create a Client for communicating with Composable Commerce
Description:
This factory will create a Guzzle HTTP Client preconfigured for talking to Composable Commerce
Instantiation
$config = Config::fromArray( ['client_id' => '<client_id>', 'client_secret' => '<client_secret>', 'project' => '<project>'] ); $client = ClientFactory::of()->createClient($config);
Execution
Synchronous
$request = ProductProjectionSearchRequest::of(); $response = $client->execute($request); $products = $request->mapFromResponse($response);
Asynchronous
The asynchronous execution will return a promise to fulfill the request.
$request = ProductProjectionSearchRequest::of(); $response = $client->executeAsync($request); $products = $request->mapFromResponse($response->wait());
Batch
By filling the batch queue and starting the execution all requests will be executed in parallel.
$responses = Pool::batch( $client, [ProductProjectionSearchRequest::of()->httpRequest(), CartByIdGetRequest::ofId($cartId)->httpRequest()] );
Instantiation options
Using a logger
The client uses the PSR-3 logger interface for logging requests and deprecation notices. To enable logging provide a PSR-3 compliant logger (e.g. Monolog).
$logger = new \Monolog\Logger('name'); $logger->pushHandler(new StreamHandler('./requests.log')); $client = ClientFactory::of()->createClient($config, $logger);
Using a cache adapter
The client will automatically request an OAuth token and store the token in the provided cache.
It's also possible to use a different cache adapter. The SDK provides a Doctrine, a Redis and an APCu cache adapter. By default the SDK tries to instantiate the APCu or a PSR-6 filesystem cache adapter if there is no cache given. E.g. Redis:
$redis = new \Redis(); $redis->connect('localhost'); $client = ClientFactory::of()->createClient($config, null, $cache);
Using cache and logger
$client = ClientFactory::of()->createClient($config, $logger, $cache);
Using a custom cache adapter
class <CacheClass>Adapter implements \Psr\Cache\CacheItemPoolInterface { protected $cache; public function __construct(<CacheClass> $cache) { $this->cache = $cache; } } $client->getAdapterFactory()->registerCallback(function ($cache) { if ($cache instanceof <CacheClass>) { return new <CacheClass>Adapter($cache); } return null; });
Using a custom client class
If some additional configuration is needed or the client should have custom logic you could provide a class name to be used for the client instance. This class has to be an extended Guzzle client.
$client = ClientFactory::of()->createCustomClient(MyCustomClient::class, $config);
Middlewares
Adding middlewares to the clients for Composable Commerce as well for the authentication can be done using the config by setting client options.
Using a HandlerStack
$handler = HandlerStack::create(); $handler->push(Middleware::mapRequest(function (RequestInterface $request) { ... return $request; }) ); $config = Config::of()->setClientOptions(['handler' => $handler])
Using a middleware array
$middlewares = [ Middleware::mapRequest(function (RequestInterface $request) { ... return $request; }), ... ] $config = Config::of()->setClientOptions(['middlewares' => $middlewares])
Timeouts
The clients are configured to timeout by default after 60 seconds. This can be changed by setting the client options in the Config instance
$config = Config::of()->setClientOptions([ 'defaults' => [ 'timeout' => 10 ] ])
Another option is to specify the timeout per request
$request = ProductProjectionSearchRequest::of(); $response = $client->execute($request, null, ['timeout' => 10]);
Retrying
As a request can error in multiple ways it's possible to add a retry middleware to the client config. E.g.: Retrying in case of service unavailable errors
$config = Config::of()->setClientOptions([ 'defaults' => [ 'timeout' => 10 ] ]) $maxRetries = 3; $clientOptions = [ 'middlewares' => [ 'retry' => Middleware::retry( function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) use ($maxRetries) { if ($response instanceof ResponseInterface && $response->getStatusCode() < 500) { return false; } if ($retries > $maxRetries) { return false; } if ($error instanceof ServiceUnavailableException) { return true; } if ($error instanceof ServerException && $error->getCode() == 503) { return true; } if ($response instanceof ResponseInterface && $response->getStatusCode() == 503) { return true; } return false; }, [RetryMiddleware::class, 'exponentialDelay'] ) ] ]; $config->setClientOptions($clientOptions);
Located at Core/Client/ClientFactory.php
Methods summary
public
|
|
public
GuzzleHttp\Client
|
#
createCustomClient( string $clientClass,
|
public
|
#
createClient(
|
public
|
#
createAuthClient( array $options = [],
|
public static
callable
|
#
reauthenticate(
Middleware that reauthenticates on invalid token error |
public static
callable
|
#
httpErrors( )
Middleware that throws exceptions for 4xx or 5xx responses when the "http_error" request option is set to true. |
public static
|