Storing data in a static class [PHP]

Hello everyone and Merry Christmas!

I'm having performance issues and I hope the StackOverflow community can help me.

In one of my (static) classes, I have a function that takes a large amount of information from my database, analyzes this information and puts it in a formatted array. Many functions in this class rely on this formatted array and throughout the class, I call it several times, which means that the application goes through these processes several times in one pass, which, I assume, is not very efficient. So I am wondering if there is a more efficient way that I can do this. Is there a way to save a formatted array in a static function, so I don’t need to reprocess the whole process every time I need information from a formatted array?

private static function makeArray(){ // grab information from database and format array here return $array; } public static function doSomething(){ $data = self::makeArray(); return $data->stuff; } public static function doSomethingElse(){ $data = self::makeArray(); return $data->stuff->moreStuff; } 
+5
source share
1 answer

If the result of makeArray() will not change during one run of your script, consider caching its result in the static property of the class after the first retrieval. To do this, check if the variable is empty. If so, do the database action and save the result. If not empty, just return the existing array.

 // A static property to hold the array private static $array; private static function makeArray() { // Only if still empty, populate the array if (empty(self::$array)) { // grab information from database and format array here self::$array = array(...); } // Return it - maybe newly populated, maybe cached return self::$array; } 

You can even add a boolean parameter to a function that forces a new copy of the array.

 // Add a boolean param (default false) to force fresh data private static function makeArray($fresh = false) { // If still empty OR the $fresh param is true, get new data if (empty(self::$array) || $fresh) { // grab information from database and format array here self::$array = array(...); } // Return it - maybe newly populated, maybe cached return self::$array; } 

All of your other class methods may continue to call self::makeArray() , as you have already done.

 public static function doSomething(){ $data = self::makeArray(); return $data->stuff; } 

If you have added an optional fresh parameter and want to force the extract from the database

 public static function doSomething(){ // Call normally (accepting cached values if present) $data = self::makeArray(); return $data->stuff; } public static function doSomethingRequiringRefresh(){ // Call with the $fresh param true $data = self::makeArray(true); return $data->stuff; } 
+3
source

Source: https://habr.com/ru/post/1239231/


All Articles