Using the Sync API with PHP
The sync API allows you to keep a local copy of all content of a space up-to-date via delta updates. This tutorial will walk you how to use the Sync API with the Contentful PHP SDK.
Please note: the Sync API is currently supported only when using the master
branch. When trying to perform sync-related operations on a client which is configured with any other environment, a \RuntimeException
will be thrown.
Getting started
After you've installed the SDK you need to set up the client and get an instance of the synchronization manager. For this tutorial we'll be using an example space.
$client = new \Contentful\Delivery\Client($accessToken, $spaceId);
$syncManager = $client->getSynchronizationManager();
Now we're able to start the initial synchronization.
$result = $syncManager->startSync();
$items = $result->getItems();
As this is the initial sync $items
will contain the entries and assets of your space. Storing these objects to the filesystem or a database will be left to you. To make it somewhat easier, all objects can be serialized to JSON and later rebuilt:
$json = \json_encode($items[0]);
$object = $client->parseJson($json);
If you have a space that's bigger than the example space, the sync might involve more records that can't be handled with one API call. To get absolutely everything you have to check $result->isDone()
:
$result = $syncManager->startSync();
while (!$result->isDone()) {
$result = $syncManager->continueSync($result);
}
Continuing the sync
To be able to get new changes later, you need to save the last token after the initial synchronization is complete. Using this token you can then resume the synchronization at the last state you've saved.
$token = $result->getToken();
// Whenever you want to sync again
$result = $syncManager->continueSync($token);
When continuing the sync you might encounter instances of the classes DeletedEntry
and DeletedEntry
. These give you access to some metadata, most importantly the ID, to delete the resources from your local storage.
Complete sync
The SDK also provides a way for transparently performing a full sync:
foreach ($syncManager->sync() as $result) {
$items = $result->getItems();
// Do something...
}
The method sync
does not perform all queries at once. In fact, internally it uses yield
to pause execution and return the current result object. This means that your foreach
loop will be responsive immediately, and the next query will be executed on the next iteration.
Conclusion
With this information you should be able to implement a solution syncing your content to local storage. If you run into any trouble please open an issue.
You can find the Contentful PHP SDK on GitHub.