Skip to content

Instantly share code, notes, and snippets.

@acrosman
Created May 6, 2017 18:59
Show Gist options
  • Save acrosman/5f0d0a04ec3da226a17dbf7937a96ef9 to your computer and use it in GitHub Desktop.
Save acrosman/5f0d0a04ec3da226a17dbf7937a96ef9 to your computer and use it in GitHub Desktop.
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