In my book Learning Drupal as a framework, we learn some nice things about cacheable dependencies. Recently I had to provide a JSON controller with cached data. Here is an example:
<?php
namespace Drupal\platform_custom\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Component\Serialization\Json;
/**
* Class PlatformJsonController
* @package Drupal\platform_custom\Controller
*/
class PlatformJsonController {
/**
* @return JsonResponse
*/
public function render() {
$config = \Drupal::config('platform_custom.customconfig')->get('platform_data');
$decoded = Json::decode($config);
$response = new CacheableJsonResponse($decoded, 200);
$response->addCacheableDependency(\Drupal::config('platform_custom.customconfig'));
return $response;
}
}
This JSON page will only invalidate its caches when the config gets changed in the back-end.