Drupal caching

 Use case1:

You return data as a JSON API via an endpoint. Ex: /api/mydata. This data is fetched from a config form.

Now, we have to cache the JSON API response and refresh it when the config form is updated.

Code:

$config = $this->config(MySettingsForm::my_config_name);

$cacheMeta = new CacheableMetadata();

$cacheMeta->addCacheTags($config->getCacheTags());

$data = ['key' => 'value'];

$response = new CacheableJsonResponse(json_encode([$data], JSON_UNESCAPED_SLASHES), 200, [], TRUE);

$response->addCacheableDependency($cacheMeta);

return $response;

When this code is added to the controller, Drupal stores following cache id (cid) in cache_config table when the response is created for the first time. For subsequent requests the cached data is returned. When the config form is updated the cached data is refreshed using the cache id (cid)

cache id:

config:my_module.my_config_name 

Comments

Popular posts from this blog

Programatically create layout builder section in Drupal

Code quality analysis of Drupal. Can I use Sonar?

Set up Drupal7 to Drupal8 migration in simple steps (using Drush)