Drupal EntityFieldQuery, drupal_static(), \Drupal::cache() Example

This function gets all the Media ID's from the database whose names begins with a specific string. I'm using this for an array of default images.

You can see I'm using both drupal_static() and \Drupal::cache(). Necessary? I would bet \Drupal::cache() goes to the database to ask for information (unless you're using Memcache or Redis, that is), and thus in a view with multiple content listings calling this function drupal_static() will be faster, because that saves to a PHP variable. Overkill for a little query like this? OK, sue me. I love performance.

Here's the code. I did this with PHP constants because the settings are site-wide and I wanted others devs to be able to see and change them. More proper would be a client-configurable config object and interface, but that's not requirements right now.

// Media entries will be pulled from the DB whose name begins with this.
define('DEFAULT_MEDIA_SEARCH_PREFIX', 'Default Image: ');
 
// How long to cache media defaults? Fed to strtotime()
define('DEFAULT_MEDIA_CACHE_EXPIRY', '+2 days');
 
/**
 * @param string $search_prefix The string that precedes Media Names
 *
 * @return array of ints representing Media ids
 */
function mytheme_get_default_image_ids($search_prefix = DEFAULT_MEDIA_SEARCH_PREFIX) {
  $cid = 'emulsify:get_default_image_ids';
  $mids = &drupal_static($cid);
  if (!isset($mids)) {
    if ($mids = \Drupal::cache()->get($cid) && !empty($mids['data'])) {
      return $mids['data'];
    }
    else {
      $query = \Drupal::entityQuery('media');
      $mids = $query->condition('status', 1)
                    ->condition('name', $search_prefix, 'STARTS_WITH')
                    ->condition('bundle', 'image')
                    ->execute();
      \Drupal::cache()->set($cid, $mids, strtotime(DEFAULT_MEDIA_CACHE_EXPIRY));
      return $mids;
    }
  }
}

Sources:

About the Author

Hi. My name is Jeremiah John. I'm a sf/f writer and activist.

I just completed a dystopian science fiction novel. I run a website which I created that connects farms with churches, mosques, and synagogues to buy fresh vegetables directly and distribute them on a sliding scale to those in need.

In 2003, I spent six months in prison for civil disobedience while working to close the School of the Americas, converting to Christianity, as one does, while I was in the clink.