cam*_*mps 6 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;
}
Run Code Online (Sandbox Code Playgroud)
如果预计 的结果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;
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以向函数添加一个布尔参数,以强制数组的新副本。
// 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;
}
Run Code Online (Sandbox Code Playgroud)
所有其他类方法都可以self::makeArray()
像您已经完成的那样继续调用。
public static function doSomething(){
$data = self::makeArray();
return $data->stuff;
}
Run Code Online (Sandbox Code Playgroud)
如果您添加了可选的 fresh 参数并希望强制从数据库检索
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;
}
Run Code Online (Sandbox Code Playgroud)