views:

89

answers:

3

I have multiple blocks shown on the user profile page, user/uid

On each of them, I need to print the user name.

I've been doing a $user = user_load(arg(1)); print $user->name; on each block. Since there is no caching, as you can image the performance is HORRIBLE.

Is there either a way to get the user name more efficiently or to cache user_load.

Thanks.

A: 

The user is a global.

function myfunction() { global $user; }

Rimian
$user is current user, not a current profile page user.
Nikit
A: 

http://alexisyes.com/2008/11/25/how-cache-usernames

Nikit
great google-fu! :D
Mark
+2  A: 

Just add an intermediate function to provide the static caching yourself:

/**
 * Proxy for user_load(), providing static caching
 * NOTE: Only works for the common use of user_load($uid) - will NOT load by name or email
 *
 * @param int $uid - The uid of the user to load
 * @param bool $reset - Wether to reset the static cache for the given uid, defaults to FALSE
 * @return stdClass - A fully-loaded $user object upon successful user load or FALSE if user cannot be loaded.
 */
function yourModule_user_load_cached($uid, $reset = FALSE) {
  static $users = array();

  // Do we need to (re)load the user?    
  if (!isset($users[$uid]) || $reset) {
    $users[$uid] = user_load($uid);
  }

  return $users[$uid];
}
Henrik Opel