Cleanest/Fastest way to avoid calling and retrieving data from the database multiple times?

It’s a great question. There is a simple and not so clean way to go, and there is a cleaner way to go that is more complicated.

Simple, dirty way to go

You can declare global variables in PHP that will be available anywhere in PHP in this pageload. So for example, the first time you do the call you can say:

global $store_last_order;
$store_last_order = wc_get_customer_last_order();

Then any time you need the last order instead of calling that function again, you just use this:

global $store_last_order; // get access to this again
do_something($store_last_order);

Good things: This is quick and easy.

Bad things: You have to make sure you know where the variable is used first so you set it in that place first, then other places use it after that, or you set it once before anyone uses it.

Better

You could also use a PHP array to pass around all the information you need. E.g. make this once at the top of functions.php or somewhere before it’s needed:

$important_stuff = [ 'last_order' => get_last_order(),
                     'customer_info' => get_customer_info() ]
                      ....
                   ];

Then whenever you need one of those things, make sure you have access to $important_stuff somehow (pass it in the function call or make it a global if you have to), then do:

do_something($important_stuff['last_order']) ; // e.g. to get last_order

** Good ** This is cleaner and fast and easier to write

** Bad ** This may get out of hand if it gets very big. You have to pass around a reference to $important_stuff everywhere

Best, More Complicated

You could write your own PHP class which takes care of storing all this information, and which takes care of stuff like getting the information if it doesn’t already have it.

E.g.:

$myStore = get_my_data_store();
$last_order = $myStore->get_last_order();

Then inside this class perhaps it’s doing something like:

function get_last_order() {
     if (already got the last order before) {
           return last order;
     } else {
           get last order
           return last order;
     }
}

Good: This is much cleaner code and more more extensible to save you money and time later if you expand it. You’ll become a better developer and you’ll be able to do more stuff faster in the future

Bad: This is much more code to write and you have to learn about things like PHP Singletons and using Classes in PHP

Leave a Comment