commercetools / php-sdk
This Composable Commerce PHP SDK is deprecated effective 1st September 2022. We recommend you to use our new SDK here https://docs.commercetools.com/sdk/php-sdk#php-sdk-v2.
Installs: 256 369
Dependents: 17
Suggesters: 0
Security: 0
Stars: 43
Watchers: 63
Forks: 21
Open Issues: 29
Type:project
Requires
- php: >=5.6
- ext-intl: *
- cache/apcu-adapter: ^1.0 || ^0.3 || ^0.2
- guzzlehttp/guzzle: ^7.0 || ^6.0 || ^5.3.3
- guzzlehttp/psr7: ^1.7 || ^2.0
- paragonie/random_compat: ^2.0 || ^1.0 || ^9.99
- psr/cache: ^1.0 || ^2.0 || ^3.0
- psr/log: ^1.0 || ^2.0
- psr/simple-cache: ^1.0
Requires (Dev)
- cache/adapter-common: ^1.0
- cache/apcu-adapter: ^1.0
- cache/array-adapter: ^1.0
- cache/doctrine-adapter: ^1.0
- cache/filesystem-adapter: ^1.0
- cache/redis-adapter: ^1.0
- cache/void-adapter: ^1.0
- commercetools/commercetools-api-reference: dev-main
- doctrine/cache: ^1.6 || ^2.0
- guzzlehttp/guzzle: ^7.0 || ^6.0
- monolog/monolog: ^1.12 || ^2.0
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: 9.5.10
- symfony/stopwatch: ^4.0 || ^3.4.38 || ^5.0
- symfony/yaml: ^4.0 || ^3.4.38 || ^5.0
- symplify/easy-coding-standard: 10.0.2
Suggests
- cache/doctrine-adapter: For usage of a doctrine cache instance to store the client access token
- cache/redis-adapter: For usage of a redis server to store the client access token
Replaces
- dev-main
- v2.22.0
- v2.21.0
- v2.20.0
- v2.19.0
- v2.18.0
- 2.17.x-dev
- v2.17.1-beta.2
- 2.17.1-beta.1
- v2.17.0
- v2.16.0
- v2.15.0
- v2.14.0
- v2.13.0
- v2.12.1
- v2.12.0
- 2.11.x-dev
- v2.11.1
- v2.11.0
- v2.10.0
- v2.9.0
- v2.8.0
- v2.7.0
- v2.6.0
- v2.5.1
- v2.5.0
- v2.4.0
- v2.3.0
- v2.2.1
- v2.2.0
- v2.1.0
- v2.0.0
- v2.0-RC1
- 1.7.x-dev
- v1.7.1
- v1.7.0
- v1.6.1
- v1.6.0
- v1.5.1
- v1.5.0
- v1.4.0
- v1.3.1
- v1.3.0
- v1.2.3
- v1.2.2
- v1.2.1
- v1.2.0
- v1.1.1
- v1.1.0
- v1.0.1
- v1.0.0
- v1.0.0-RC12
- v1.0.0-RC11.1
- v1.0.0-RC11
- v1.0.0-RC10
- v1.0.0-RC9
- v1.0.0-RC8
- v1.0.0-RC7
- v1.0.0-RC6
- v1.0.0-RC5
- v1.0.0-RC4
- v1.0.0-RC3
- v1.0.0-RC2
- v1.0.0-RC1
- v1.0.0-beta.2
- v1.0.0-beta.1
- v1.0.0-alpha.6
- v1.0.0-alpha.5
- v1.0.0-alpha.4
- v1.0.0-alpha.3
- v1.0.0-alpha.2
- v1.0.0-alpha.1
- dev-renovate/phpunit-phpunit-10.x
- dev-renovate/all
- dev-renovate/actions-checkout-4.x
- dev-renovate/conventional-changelog-cli-4.x
- dev-renovate/psr-simple-cache-3.x
- dev-renovate/psr-log-3.x
- dev-renovate/major-symfony
- dev-renovate/monolog-monolog-3.x
- dev-renovate/actions-upload-artifact-3.x
- dev-renovate/actions-cache-3.x
- dev-order-search
- dev-php-mantainance
- dev-product-selection
- dev-test-review
- dev-memory_test
- dev-releasev213
- dev-get-cart-by-customerid-uri-change
- dev-support_deleteAfterDays_ApiClients_#512
- dev-release/v2.4.0
- dev-refactor_config_class
- dev-release/v2.3.0
- dev-hotfix/v2.2.1
- dev-release/v2.2.0
- dev-release/v2.1.0
- dev-release/v2.0.0
- dev-release/v2.0-RC1
- dev-release/v1.7.0
- dev-release/v1.6.0
- dev-release/v1.5.0
- dev-release/v1.4.0
- dev-release/v1.3.0
- dev-release/v1.2.0
- dev-release/v1.1
- dev-release/v1.0.0-RC12
- dev-release/v1.0.0-RC11
- dev-release/v1.0.0-RC10
- dev-release/v1.0.0-RC9
- dev-release/v1.0.0-RC8
This package is auto-updated.
Last update: 2023-11-19 10:12:13 UTC
README
⚠️ **This Composable Commerce PHP SDK is deprecated effective 1st September 2022.
, We recommend to use our PHP SDK V2.
The PHP SDK allows developers to integrate with Composable Commerce APIs using PHP native interfaces, models and helpers instead of manually using the HTTP and JSON API.
You gain lots of IDE Auto-Completion, type checks on a literal API, Warnings, Object Mapping, i18n support etc.. The Client manages the OAuth2 security tokens, provides caches and interfaces for concurrent and asynchronous API calls.
The SDK is licensed under the permissive MIT License. Don't hesitate to contribute!
Using the SDK
The PHP API documentation provides all the details you need in a searchable form (link points to latest stable release).
Install & Integrate the SDK into your Project
The SDK requires a PHP version of 5.6 or higher. The SDK tries to use the APC(u) as it's default cache. If you provide a PSR-6 or PSR-16 compliant cache adapter, APC(u) is not necessary. The cache/filesystem-adapter is tried to be used if no APC(u) is installed.
The curl extension is recommended but not strictly necessary because the SDK is using the Guzzle library library, which falls back to PHP stream wrappers if curl is not available. The intl extension is required to directly output Money objects as a String.
The recommended way to install the SDK is through Composer.
# Install Composer if not installed yet curl -sS https://getcomposer.org/installer | php
Next, run the Composer command to install the latest version of the SDK:
composer require commercetools/php-sdk
The SDK supports Guzzle6 as well as Guzzle5 as HTTP client. For Guzzle6:
composer require guzzlehttp/guzzle ^6.0
When you want to use Guzzle5 you have to ensure react/promise at minimum version 2.2:
composer require guzzlehttp/guzzle ^5.3.1 composer require react/promise ^2.2
After installing, you need to require Composer's autoloader if that's not yet the case:
require 'vendor/autoload.php';
If you don't use Composer, just download a zip archive of the latest release, manually integrate it and configure your own autoloader.
The project follows the semantic versioning guidelines, i.e. everything but major version changes are backwards-compatible. This matches composer's default behavior.
With composer just run composer update commercetools/php-sdk
to update to compatible versions. Edit your composer.json
file to update to incompatible versions.
Please read the Changelog before updating in any case.
Getting started
To get up and running, create a free test Project on Composable Commerce. You can create your first API Client in The Merchant Center (Menu "Settings"->"Developer settings"->"Create new API client"). You need to select the template for the "Admin client".
<?php require '../vendor/autoload.php'; use Commercetools\Core\Builder\Request\RequestBuilder; use Commercetools\Core\Client; use Commercetools\Core\Config; use Commercetools\Core\Model\Common\Context; $config = [ 'client_id' => 'my client id', 'client_secret' => 'my client secret', 'project' => 'my project id' ]; $context = Context::of()->setLanguages(['en'])->setLocale('en_US')->setGraceful(true); $config = Config::fromArray($config)->setContext($context); /** * create a search request and a client, * execute the request and get the PHP Object * (the client can and should be re-used) */ $search = RequestBuilder::of()->productProjections()->search() ->addParam('text.en', 'red'); $client = Client::ofConfig($config); $products = $client->execute($search)->toObject(); /** * show result (would be a view layer in real world) */ header('Content-Type: text/html; charset=utf-8'); foreach ($products as $product) { echo $product->getName()->en . '<br/>'; }
If you prefer not to have a client with all admin rights, you need to explicitly include the client's permission scopes that you selected when creating the client, on the client's configuration:
<?php $config = [ 'client_id' => 'my client id', 'client_secret' => 'my client secret', 'project' => 'my project id', 'scope' => 'permission_scope and_another_scope' ];
In projects you will not put your API credentials directly into code but use a config file or your framework's config or dependency injection system for that.
Using the client factory
When using a Guzzle version of 6 or greater, it's also possible to use a preconfigured Guzzle client using the client factory. At the moment this is limited to client credentials authentication flow.
<?php require '../vendor/autoload.php'; use Commercetools\Core\Builder\Request\RequestBuilder; use Commercetools\Core\Client\ClientFactory; use Commercetools\Core\Config; use Commercetools\Core\Error\ApiException; use Commercetools\Core\Model\Common\Context; $config = [ 'client_id' => 'my client id', 'client_secret' => 'my client secret', 'project' => 'my project id' ]; $context = Context::of()->setLanguages(['en'])->setLocale('en_US')->setGraceful(true); $config = Config::fromArray($config)->setContext($context)->setThrowExceptions(true); /** * create a search request and a client, * execute the request and get the PHP Object * (the client can and should be re-used) */ $request = RequestBuilder::of()->productProjections()->search() ->addParam('text.en', 'red'); $client = ClientFactory::of()->createClient($config); try { $response = $client->execute($request); } catch (ApiException $exception) { throw new \Exception("Ooops! Something happened.", 0, $exception); } $products = $request->mapFromResponse($response); header('Content-Type: text/html; charset=utf-8'); foreach ($products as $product) { echo $product->getName()->en . '<br/>'; }
Synchronous execution
$request = ProductProjectionSearchRequest::of(); $response = $client->execute($request); $products = $request->mapFromResponse($response);
Asynchronous execution
The asynchronous execution will return a promise to fulfill the request.
$response = $client->executeAsync(ProductProjectionSearchRequest::of()); $products = $request->mapFromResponse($response->wait());
Batch execution
By filling the batch queue and starting the execution all requests will be executed in parallel.
$responses = GuzzleHttp\Pool::batch( $client, [ProductProjectionSearchRequest::of()->httpRequest(), CartByIdGetRequest::ofId($cartId)->httpRequest()] );
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, $logger, $redis);
Using cache and logger
$client = ClientFactory::of()->createClient($config, $logger, $cache);
Middlewares
Adding middlewares to the clients for Composable Commerce as well for the authentication can be done using the config by setting client options.
For using a custom HandlerStack
$handler = HandlerStack::create(); $handler->push(Middleware::mapRequest(function (RequestInterface $request) { ... return $request; }) ); $config = Config::of()->setClientOptions(['handler' => $handler])
For using an array of middlewares
$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);
Using the phar distribution
Since version 1.6 the SDK is also released as a PHAR. You can find them in the releases section at Github.
Usage example:
<?php require __DIR__ . '/commercetools-php-sdk.phar'; use Commercetools\Core\Client\ClientFactory; use Commercetools\Core\Builder\Request\RequestBuilder; $config = \Commercetools\Core\Config::fromArray([ 'client_id' => 'myClientId', 'client_secret' => 'myClientSecret', 'project' => 'myProjectId' ]); $client = ClientFactory::of()->createClient($config); $request = RequestBuilder::of()->project()->get(); $response = $client->execute($request); $project = $request->mapFromResponse($response); var_dump($project->toArray());
Improve & Contribute to the SDK project
Mac OS X preparations:
assuming Homebrew is installed, do the following:
xcode-select --install brew tap homebrew/dupes brew tap homebrew/versions brew tap homebrew/homebrew-php brew install php56 brew install php56-intl brew install php56-xdebug brew install ant # you probably also need to fix a (=any) timezone in your php.ini: echo "date.timezone='Europe/Berlin'" >> /usr/local/etc/php/5.6/conf.d/60-user.ini # initialize the dependencies: php composer.phar update
Linux preparations :
- install php 5.6+, xdebug and ant according to their distro's package system.
- make sure the curl, intl, mbstring and openssl extensions are activated in php.ini
Windows preparations:
- install php 5.6+, i.e. extract ZIP and make add php.exe location to your PATH. Use WAMP etc. if you like, but plain PHP commandline is all you really need (you can test example code in the built-in webserver).
- enable the curl, intl, mbstring and openssl extenstions in php.ini
- make a working ant available in the PATH
- and install composer.
Start working:
Clone the develop branch of the repository (we're using the gitflow branching model, so master is for releases only):
git clone git@github.com:commercetools/commercetools-php-sdk.git
Please follow the PSR-2 coding style, ideally via your IDE settings (see below for PhpStorm instructions).
Please make sure that exiting Unit and Integration tests don't fail and fully cover your new code with Unit Tests. You can run all tests locally:
ant
Built In Test Server
You can use the docroot
directory with the built-in PHP web server. Add to the docroot directory a file called "myapp.yml". Add following content and setup with your API credentials:
parameters: client_id: my client id client_secret: my client secret project: my project id
Then activate the php builtin web server
cd <project_folder> php -S localhost:8000 -t docroot
Now navigate to http://localhost:8000 in your browser.
PhpStorm configuration
To enable code style checks directly in PhpStorm you have to configure the path to the phpcs at Preferences > Languages & Frameworks > PHP > Code Sniffer. Now you can enable at Preferences > Editor > Inspections > PHP the "PHP code sniffer validation" with PSR-2 standard. Change the severity if needed.
Running integration tests
For running the integration tests you need an empty Project and have to create an API client using the commercetools Merchant Center with the scopes:
manage_project
view_orders
view_products
manage_my_shopping_lists
manage_my_orders
manage_my_payments
manage_my_profile
manage_api_clients
create_anonymous_token
Local environment
composer update vendor/bin/phpunit
Using docker
Running the test image:
echo "COMMERCETOOLS_CLIENT_ID=YourClientID" > env.list echo "COMMERCETOOLS_CLIENT_SECRET=YourClientSecret" >> env.list echo "COMMERCETOOLS_PROJECT=YourProjectKey" >> env.list docker run --env-file env.list -v $PWD:/opt/app -w /opt/app --rm=true jenschude/php-test-base tools/docker-phpunit.sh
Contribute
On bigger effort changes, please open a GitHub issue and ask if you can help or get help with your idea. For typos and documentation improvements just make a pull request.
Then:
- fork the repository on GitHub
- code and add tests that cover the created code. Your code should be warning-free.
- stick to PSR-2 and and don't reformat existing code.
- make a pull request. @jenschude will review it and pull or come back to you.