Posts

Showing posts from December, 2023

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