Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple example Drupal Controller with a cached JSON Response.
<?php
namespace Drupal\example\Controller;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
class ExampleController extends ControllerBase {
public function getJson(Request $request) {
$data = [];
// Do some useful stuff to build an array of data.
// Add Cache settings for Max-age and URL context.
// You can use any of Drupal's contexts, tags, and time.
$data['#cache'] = [
'max-age' => 600,
'contexts' => [
'url',
],
];
$response = new CacheableJsonResponse($data);
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment