function drupal_render_cache_by_query

Prepares an element for caching based on a query.

This smart caching strategy saves Drupal from querying and rendering to HTML when the underlying query is unchanged.

Expensive queries should use the query builder to create the query and then call this function. Executing the query and formatting results should happen in a #pre_render callback.

Parameters

$query: A select query object as returned by db_select().

$function: The name of the function doing this caching. A _pre_render suffix will be added to this string and is also part of the cache key in drupal_render_cache_set() and drupal_render_cache_get().

$expire: The cache expire time, passed eventually to cache()->set().

$granularity: One or more granularity constants passed to drupal_render_cid_parts().

Return value

A renderable array with the following keys and values:

  • #query: The passed-in $query.
  • #pre_render: $function with a _pre_render suffix.
  • #cache: An associative array prepared for drupal_render_cache_set().
2 calls to drupal_render_cache_by_query()
ActiveTopicsBlock::build in drupal/core/modules/forum/lib/Drupal/forum/Plugin/Block/ActiveTopicsBlock.php
Builds and returns the renderable array for this block plugin.
NewTopicsBlock::build in drupal/core/modules/forum/lib/Drupal/forum/Plugin/Block/NewTopicsBlock.php
Builds and returns the renderable array for this block plugin.

File

drupal/core/includes/common.inc, line 5093
Common functions that many Drupal modules will need to reference.

Code

function drupal_render_cache_by_query($query, $function, $expire = CacheBackendInterface::CACHE_PERMANENT, $granularity = NULL) {
  $cache_keys = array_merge(array(
    $function,
  ), drupal_render_cid_parts($granularity));
  $query
    ->preExecute();
  $cache_keys[] = hash('sha256', serialize(array(
    (string) $query,
    $query
      ->getArguments(),
  )));
  return array(
    '#query' => $query,
    '#pre_render' => array(
      $function . '_pre_render',
    ),
    '#cache' => array(
      'keys' => $cache_keys,
      'expire' => $expire,
    ),
  );
}