Forum OpenACS Q&A: util_memoize proc

Collapse
Posted by David Kuczek on
Supposing I want to know on every page to what kind of user_group the
user belongs to. I have 5 distinct users_groups and each user has to
belong to exactly one group. As I query this information on every page
I thought of util_memoizing it to get the job done quicker.

But does util_memoize work for individual queries? Or should it only
be used with queries that show the same output to everybody?

Is there any other way I can get this information on every page and
not having to query all the time?

Thanks

Collapse
Posted by Carl Coryell-Martin on
This probably depends on how many users and how much ram you have. If you are like most of us, you probably have far more ram than users and can easily memoize the group for each user.

I would probably write a little proc like this:

proc_doc users_special_group { user_id {db ""} } "Little proc to 
return the special group the user is a member of." {
   set release 0
   if ![exists_and_not_null db] {
      set db [ns_db gethandle]
      set release 1
   }
   set special_group [database_to_tcl_string $db "select ..... "]
    if $release {
      ns_db releasehandle $db
   }
   return $special_group
}
What is nice about this is now you can do util_memize "user_special_group $user_id" and not have to have a separate entry in the memory for each user + db handle. NB: you might want to add additional error correction...

(I would love comments on better ways to do this. I have abstracted the db handle logic into little helper procs)

This will work pretty darn well. now on each page you can just call [util_memoize "..."] and if an entry doesn't exist it will create one. This would be my approach. (Unless you are using the ATS which has some built in caching tools.)

Cheers,