Composable Commerce PHP SDKPHP SDK
  • Namespace
  • Class
  • Tree

Namespaces

  • Commercetools
    • Commons
      • Helper
    • Core
      • Builder
        • Request
        • Update
      • Cache
      • Client
        • Adapter
        • OAuth
      • Error
      • Helper
        • Annotate
        • State
          • Renderer
        • Subscriber
          • Log
      • Model
        • ApiClient
        • Cart
        • CartDiscount
        • Category
        • Channel
        • Common
        • Customer
        • CustomerGroup
        • CustomField
        • CustomObject
        • DiscountCode
        • Extension
        • Inventory
        • Message
        • Order
        • OrderEdit
        • Payment
        • Product
          • Search
        • ProductDiscount
        • ProductSelection
        • ProductType
        • Project
        • Review
        • ShippingMethod
        • ShoppingList
        • State
        • Store
        • Subscription
        • TaxCategory
        • Type
        • Zone
      • Request
        • ApiClients
        • CartDiscounts
          • Command
        • Carts
          • Command
        • Categories
          • Command
        • Channels
          • Command
        • CustomerGroups
          • Command
        • Customers
          • Command
        • CustomField
          • Command
        • CustomObjects
        • DiscountCodes
          • Command
        • Extensions
          • Command
        • GraphQL
        • InStores
        • Inventory
          • Command
        • Me
          • Command
        • Messages
        • OrderEdits
          • Command
          • StagedOrder
            • Command
        • Orders
          • Command
        • Payments
          • Command
        • ProductDiscounts
          • Command
        • Products
          • Command
        • ProductSelections
          • Command
        • ProductTypes
          • Command
        • Project
          • Command
        • Query
        • Reviews
          • Command
        • ShippingMethods
          • Command
        • ShoppingLists
          • Command
        • States
          • Command
        • Stores
          • Command
        • Subscriptions
          • Command
        • TaxCategories
          • Command
        • Types
          • Command
        • Zones
          • Command
      • Response

Classes

  • ApiClient
  • ClientFactory
  • HttpMethod
  • ProviderFactory
  • UserAgentProvider

Interfaces

  • HttpRequestInterface

Class ClientFactory

The factory to create a Client for communicating with Composable Commerce

Namespace: Commercetools\Core\Client
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
# __construct( )

ClientFactory constructor.

ClientFactory constructor.

Throws

Commercetools\Core\Error\DeprecatedException
public GuzzleHttp\Client
# createCustomClient( string $clientClass, Commercetools\Core\Config|array $config, Psr\Log\LoggerInterface $logger = null, Psr\Cache\CacheItemPoolInterface|Psr\SimpleCache\CacheInterface $cache = null, Commercetools\Core\Client\OAuth\TokenProvider $provider = null, Commercetools\Core\Cache\CacheAdapterFactory $cacheAdapterFactory = null, Commercetools\Core\Model\Common\Context $context = null )

Parameters

$clientClass
$config
$logger
$cache
$provider
$cacheAdapterFactory
$context

Returns

GuzzleHttp\Client
public Commercetools\Core\Client\ApiClient
# createClient( Commercetools\Core\Config|array $config, Psr\Log\LoggerInterface $logger = null, Psr\Cache\CacheItemPoolInterface|Psr\SimpleCache\CacheInterface $cache = null, Commercetools\Core\Client\OAuth\TokenProvider $provider = null, Commercetools\Core\Cache\CacheAdapterFactory $cacheAdapterFactory = null, Commercetools\Core\Model\Common\Context $context = null )

Parameters

$config
$logger
$cache
$provider
$cacheAdapterFactory
$context

Returns

Commercetools\Core\Client\ApiClient
public
# createAuthClient( array $options = [], Commercetools\Core\Helper\CorrelationIdProvider $correlationIdProvider = null )
public static callable
# reauthenticate( Commercetools\Core\Client\OAuth\OAuth2Handler $oauthHandler, integer $maxRetries = 1 )

Middleware that reauthenticates on invalid token error

Middleware that reauthenticates on invalid token error

Parameters

$oauthHandler
$maxRetries

Returns

callable
Returns a function that accepts the next handler.
public static callable
# httpErrors( )

Middleware that throws exceptions for 4xx or 5xx responses when the "http_error" request option is set to true.

Middleware that throws exceptions for 4xx or 5xx responses when the "http_error" request option is set to true.

Returns

callable
Returns a function that accepts the next handler.
public static Commercetools\Core\Client\ClientFactory
# of( )

Returns

Commercetools\Core\Client\ClientFactory
PHP SDK API documentation generated by ApiGen