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

时间:2015-12-26 01:52:12

标签: php database class persistent static-classes

大家好,圣诞快乐!

我在效率方面遇到了一些麻烦,我希望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;
}

1 个答案:

答案 0 :(得分:3)

如果在一次运行脚本期间预计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;
}
相关问题