I am reading up on the Cache API, and have a question about caching users (or objects in general) in the DB, i.e. the cache_default MySQL table.
Please consider the following simple function to retrieve a User object (I know this type of code should probably live in a custom service, but am using a function here, just for clarity):
<?php
/**
* Get a user object
* @param Integer
* @return User
*/
function get_user_data($uid)
{
if ($uid) {
$cache_id = 'my_user:' . $uid;
$user = NULL;
if ($cache = \Drupal::cache()->get($cache_id)) {
// Read user object from the default cache.
$user = $cache->data;
}
else {
// user not found in the cache.
$user = \Drupal\user\Entity\User::load($uid);
// Cache tags from User object, to tell Drupal to invalidate the cache
// data after any change to the user.
$user_cache_tags = $user->getCacheTags();
// Store a serialized user object in the default cache.
\Drupal::cache()->set($cache_id, $user, Cache::PERMANENT, $user_cache_tags);
}
return $user;
}
return FALSE;
}
My goal is to cache a Drupal User object, that also depends on large amounts of data in multiple profiles (using the Profiles module).
The User for my use case might actually require more properties, or some way to an interface with Profile objects, and thus may need to extend User (a "MyUser" class etc), but the design of our objects is out of scope for this question.
My question is:
Does the above code accomplish anything useful? (Or Is Drupal already caching User objects somewhere, and the above code accomplishes nothing?)
Also assume for my use case:
- I am not able to use Redis or Memcached.
- My Drupal application must rely on many very cumbersome database queries (to read user tables, profile tables) every time I need to gather user data.
Thank you in advance.