Get started with the PHP SDK

Learn how to set up and use the PHP SDK.

This step-by-step guide leads you through setting up and making API calls using the PHP SDK.

Requirements

To follow this guide you should have the following:

For more information on setting up a commercetools Composable Commerce Project or API Client, follow our Getting started with commercetools Composable Commerce guides.

Objectives of the get started guide

After following this guide you will have:

Placeholder values

Example code in this guide uses placeholders that should be replaced with the following values.

If you do not have an API Client, follow our Get your API Client guide.

PlaceholderReplace withFrom
{projectKey}project_keyyour API Client
{clientID}client_idyour API Client
{clientSecret}secretyour API Client
{scope}scopeyour API Client
{region}your RegionHosts

Install the PHP SDK

Use the following command to install the PHP SDK:

composer require commercetools/commercetools-sdk

Create the Client class

Create a file called Client.php and insert the following code:

<?php
namespace Commercetools;
// Required imports
use Commercetools\Api\Client\ApiRequestBuilder;
use Commercetools\Api\Client\ClientCredentialsConfig;
use Commercetools\Api\Client\Config;
use Commercetools\Client\ClientCredentials;
use Commercetools\Client\ClientFactory;
use GuzzleHttp\ClientInterface;
require_once __DIR__ . '/vendor/autoload.php';
class Client
{
function createApiClient()
{
/** @var string $clientID */
/** @var string $clientSecret */
/** @var string $scope
* Provide a specific scope for the client.
* If not included, all the scopes of the OAuth client will be used.
* Format: `{scope name}:{projectKey}`.
* Example: `manage_products:project1`.
*/
$authConfig = new ClientCredentialsConfig(
new ClientCredentials('{clientID}', '{clientSecret}', '{scope}'),
[],
'https://auth.{region}.commercetools.com/oauth/token'
);
$client = ClientFactory::of()->createGuzzleClient(
new Config([], 'https://api.{region}.commercetools.com'),
$authConfig
);
/** @var ClientInterface $client */
$builder = new ApiRequestBuilder($client);
// Include the Project key with the returned Client
return $builder->withProjectKey('{projectKey}');
}
}
?>

Test the Client

In your PHP program, add the following code:

<?php
namespace Commercetools;
// Include the Client
require_once 'Client.php';
// Create the apiRoot with your Client
$apiRoot = (new Client())->createApiClient();
// Make a get call to the Project
$myProject = $apiRoot->get()->execute();
// Output the Project name
echo $myProject->getName();
?>

$apiRoot can now be used to build requests to the Composable Commerce API.

This code includes an example API call that gets your Project to $myProject and outputs the Project's name using getName().

Using the PHP SDK

Imports

Without importing resource-specific classes you will be unable to use/access specific objects and methods.

For example, to create a Shopping List you must import:

use Commercetools\Api\Models\ShoppingList\ShoppingListDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';

If not imported, a "Class not found" fatal error is returned with the name of the required class.

Using builders

The PHP SDK follows a builder pattern when constructing drafts, update actions, and other objects/types that contain multiple fields.

// Imports
use Commercetools\Api\Models\Common\LocalizedStringBuilder;
use Commercetools\Api\Models\Common\MoneyBuilder;
use Commercetools\Api\Models\Category\CategoryDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Create a LocalizedString
$localizedString = LocalizedStringBuilder::of()
->put('en', 'English value')
->put('de', 'German value')
->build();
// Create US$100.00
$money = MoneyBuilder::of()
->withCurrencyCode('USD')
->withCentAmount(10000)
->build();
// Create a Category
$categoryDraft = CategoryDraftBuilder::of()
->withName(
LocalizedStringBuilder::of()
->put('en', 'English name')
->build()
)
->withSlug(
LocalizedStringBuilder::of()
->put('en', 'english-slug')
->build()
)
->withKey('category-key')
->build();

Consult the HTTP API reference to ensure that all required fields are included.

Once the fields/values are added, build() finishes building the object.

Structure your API call

Add an endpoint

An endpoint should be added to $apiRoot. The following targets the Shopping Lists endpoint:

$shoppingListInfo = $apiRoot->shoppingLists();
// ...

If your IDE supports auto-complete, the full list of endpoints can be viewed.

Screenshot of autocomplete for endpoint

If no endpoint is specified, the Project is referenced.

Retrieving data

Get a single resource

When targeting a specific resource, you should include its ID or key followed by get() and execute().

// Get a specific Shopping List by ID
$shoppingListInfo = $apiRoot
->shoppingLists()
->withId('a-shoppinglist-id')
->get()
->execute();
// Get a specific Shopping List by key
$shoppingListInfo = $apiRoot
->shoppingLists()
->withKey('a-shoppinglist-key')
->get()
->execute();

If you query a resource with an id or key that does not exist, the API returns a 404 Not Found error.

In this example, $shoppingListInfo now contains the data of the specified Shopping List. Individual information can be accessed from the fields within that object:

Screenshot of autocomplete for ShoppingList object

Get multiple resources

If no ID or key is included, then the endpoint returns a PagedQueryResponse, which is identical to the PagedQueryResults in the HTTP API.

// Return a ShoppingListPagedQueryResponse
$shoppingListQuery = $apiRoot
->shoppingLists()
->get()
->execute();

The results of these calls can be altered by including withWhere(), withSort(), withExpand(), withLimit(), or withOffset() after get().

These are identical to the parameters you can add to standard HTTP API calls. If your IDE supports autocomplete you can view a full list of methods available:

Screenshot of autocomplete for parameters

Viewing results

A list of resources within a PagedQueryResponse can be accessed using getResults():

// Return a ShoppingListPagedQueryResponse
$shoppingListQuery = $apiRoot
->shoppingLists()
->get()
->execute();
// Put the returned Shopping Lists in a collection
$collectionOfShoppingLists = $shoppingListQuery->getResults();
// Output the first Shopping List's English name
echo $collectionOfShoppingLists[0]->getName()['en'];

Writing a resource

Creating a new resource

Creating a new resource requires a draft of the resource to create. For Shopping Lists this would be a ShoppingListDraft. These drafts are created using builders.

// Required import
use Commercetools\Api\Models\ShoppingList\ShoppingListDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Build a ShoppingListDraft with the required fields (email address and password)
$newShoppingListDetails = (new ShoppingListDraftBuilder())
->withName(
(new LocalizedStringBuilder())
->put('en', 'English name of Shopping List')
->build()
)
->build();

$newShoppingListDetails should be included within post() and followed by execute().

// Post the ShoppingListDraft and get the new Shopping List
$newShoppingList = $apiRoot
->shoppingLists()
->post($newShoppingListDetails)
->execute();

Updating an existing resource

Updating an existing resource requires posting an update payload. This payload (in the case of Shopping Lists, a ShoppingListUpdate) contains a collection of update actions and the last seen version of the resource.

Update actions and payloads are created using builders.

// Required imports
use Commercetools\Api\Models\ShoppingList\ShoppingListUpdateBuilder;
use Commercetools\Api\Models\ShoppingList\ShoppingListUpdateActionCollection;
use Commercetools\Api\Models\ShoppingList\ShoppingListSetKeyActionBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Build a ShoppingListUpdate with the required fields (version and ShoppingListUpdateActionCollection)
$shoppingListUpdate = (new ShoppingListUpdateBuilder())
->withVersion(1)
->withActions(
(new ShoppingListUpdateActionCollection())->add(
(new ShoppingListSetKeyActionBuilder())
->withKey('a-unique-shoppinglist-key')
->build()
)
)
->build();

This payload must then be posted to a single resource (using withId() or withKey()).

// Post the ShoppingListUpdate and return the updated Shopping List
$updatedShoppingList = $apiRoot
->shoppingLists()
->withId('{shoppingListID}')
->post($shoppingListUpdate)
->execute();

Deleting a resource

Deleting a resource requires using the .delete() method with the last seen version of the resource. The resource to delete must be identified using withId() or withKey().

// Delete and return a Shopping List
$deletedShoppingList = $apiRoot
->shoppingLists()
->withId('{shoppingListID}')
->delete()
->withVersion(1)
->withDataErasure('true') // Include to erase related personal data
->execute();

Retrieving the raw API response

The above examples use execute() to return the resource as an instance of an object.

To retrieve the raw API response, use send().

// Return a ShoppingListPagedQueryResponse
$shoppingListQuery = $apiRoot
->shoppingLists()
->get()
->send()
->getBody();
// Output the raw API response
echo $shoppingListQuery;

Try our example code

Continue learning about the PHP SDK by checking our SDK code examples. You will find example code for creating, querying, and updating Customers and Products.