开发者

Drupal: Getting user name on user account page without breaking performance

开发者 https://www.devze.com 2022-12-23 00:52 出处:网络
I have multiple blocks shown on the user profile page, user/uid On each of them, I need to print the user name.

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.


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];
}


Use menu_get_object() which is the proper way to retrieve an object (user, node, etc.) loaded from the URL of a properly declared page. It will return the user object that has already been loaded using the uid found at arg(1) for a menu item which use %user in its path (ie. $items['user/%user'], $items['user/%user/view'], etc. in user_menu().

$account = menu_get_object('user');


The user is a global.

function myfunction() { global $user; }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号