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:
- Stack overflow post on drupal_static
- The QueryInterface page of the Drupal docs which has the actual EFQ operators
- Sitepoint's excellent overview of EntityFieldQuery in D8
- Drupal Cache API documenation