I use a field in user account to store some user variables. These variables are not accessible by the user. I am worrying about the efficient of using the user_load in every page in order to access the variables. Maybe it is better to use the variable_set() ? What is the recommended procedure of setting/accessing variables in drupal?
1 Answer
If efficiency is the goal, and your variables aren't too complex, you could take advantage of the data
property of the user entity. It's stored as a serialised string in the {users}
table and is available by default as part of the global $user
object. As it's loaded from the database for any type of user load (even the bare minimum one) you can reduce the overhead to basically nothing.
The best example of how to use it comes from the docs for hook_user_presave()
:
function hook_user_presave(&$edit, $account, $category) {
// Make sure that our form value 'mymodule_foo' is stored as
// 'mymodule_bar' in the 'data' (serialized) column.
if (isset($edit['mymodule_foo'])) {
$edit['data']['mymodule_bar'] = $edit['mymodule_foo'];
}
}
Then to retrieve the value at another point in code it's as simple as:
global $user;
$mymodule_bar = $user->data['mymodule_bar'];
Fields are great but as you know they do add overhead, so for small amounts of data I can't see any reason not to use the data
property in this way.
I think using the variables table would get unmanageable quite quickly; you'd either end up with a different variable for each user, or having to store a single variable containing all users' data...neither of which are that desirable.