Caching in the PHP CDA SDK
Content types and space data change rarely, but you want to access them very often. They are a perfect candidate for caching: you save API calls and speed up execution. Let's take a look at how to locally cache their data using the PHP CDA SDK.
Warming up the cache
The first thing we need to do is to warm up the cache. This process will save our cached JSON files locally in a directory of our choosing. From the command line:
# The command takes three parameters: # - space-id # - token # - cache-dir php vendor/bin/contentful delivery:cache:warmup cfexampleapi b4c0n73n7fu1 /my/local/cache/path
This command will generate a directory named after the space ID (in our case
cfexampleapi), and inside this directory you will find a file called
space.json and one file for every content type you have in the space (named
Configuring the client
Now that we've created the cache files, let's instruct the Client to use them. To do so, we need to specify the
cacheDir option when instantiating a new
<?php $client = new \Contentful\Delivery\Client('b4c0n73n7fu1', 'cfexampleapi', false, null, [ 'cacheDir' => '/my/local/cache/path', ]);
The fifth parameter to the constructor is an array of options: you can take a look at the source code for a detailed description of what you can do with it.
Enjoy the performance boost
That's it! Now lookups to cached
Space objects will be instantaneous. Everything happens behind the scenes, and is transparent to the developer. Should you want to refresh the cache, you can re-run te
delivery:cache:warmup command, or you can clear the cache by running:
# The command takes two parameters: # - space-id # - cache-dir php vendor/bin/contentful delivery:cache:clear cfexampleapi /my/local/cache/path
As a final note, remember one thing: should you make changes such as adding or removing a locale, or changing fields in a content type, you would need to regenerate the cache, as the SDK behavior is to use the cache whenever that's available, even at the cost of ignoring newer info. In the event of a new content type, its info would be picked up correctly — there would be nothing about it in the cache. Our suggestion is to warmup the cache at every change to the content types, so you can be sure to always have the best performance and never risk working with obsolete data.