将数据存储在静态类[PHP]中


Storing data in a static class [PHP]

大家好,圣诞快乐!

我在效率方面遇到了一些问题,我希望StackOverflow社区能帮助我。

在我的一个(静态)类中,我有一个函数,它从数据库中获取大量信息,解析这些信息并将其放入格式化的数组中。这个类中的许多函数都依赖于这个格式化的数组,在整个类中,我会多次调用它,这意味着应用程序在一次运行中会经历多次这个过程,我认为这不是很有效。所以我想知道是否有更有效的方法可以做到这一点。有没有一种方法可以将格式化的数组存储在静态函数中,这样我就不必每次需要格式化数组中的信息时都重新执行整个过程?

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;
}

如果makeArray()的结果在脚本的一次运行中预计不会更改,请考虑在第一次检索后将其结果缓存在静态类属性中。为此,请检查变量是否为空。如果是,请执行数据库操作并保存结果。如果不是空的,只返回现有数组。

// 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;
}

您甚至可以在函数中添加一个布尔参数,以强制数组的新副本。

// 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;
}

所有其他类方法都可以继续调用self::makeArray(),就像您已经做过的那样。

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

如果您添加了可选的新鲜参数,并希望强制从数据库中检索

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;
}