Created
May 6, 2017 18:59
-
-
Save acrosman/5f0d0a04ec3da226a17dbf7937a96ef9 to your computer and use it in GitHub Desktop.
A simple example Drupal Controller with a cached JSON Response.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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