More efficient use of function by storing the result? So I have a custom module that is simply one function that during Commerce checkout goes through the order or cart to create an array saying how many "products" of type 'event','donation' and 'product' there are in the cart.

Now this all works great and I use it to do multiple things such as:


Change the title page of the checkout if someone is "donating" rather
than "purchasing"
Show or hide certain checkout panes depending on whether a 'donation' or 'event' is in the cart
Render a checkout progress bar which shows certain checkout pages, again dependent on the product types currently in the cart.


My issue now is that on render of the Checkout Details page I have this one function executing 4 separate time. How would I go about triggering it once for each load of a page and storing the array in a place that can be accessed by multiple modules and template files?
Seeing as how the data is not really an item that is cachable sitewide, you could quite easily use the $_SESSION variable.

Example:

function my_expensive_function($foo, $bar) {
  if (isset($_SESSION['my_really_cool_stuff'])) {
    return $_SESSION['my_really_cool_stuff'];
  }
  else {
    //Do what you would normally do to get everything you need
    //and put it in a $my_really_cool_stuff variable
    $_SESSION['my_really_cool_stuff'] = $my_really_cool_stuff;
    return $my_really_cool_stuff;
  }
}


This way, if the data already exists in the user session, it'll return that.  If not, then it'll generate it, put it in the session, and then return it.

You can put the $_SESSION data into a theme function and make it available to templates as well if you wish, but that's probably a separate question (and you'd have to make sure you had a fallback in case the session data had not been set).