V
V
vitaly_742021-07-06 20:13:13
PHP
vitaly_74, 2021-07-06 20:13:13

How to cache variables at php level?

there is this code:

static $graph = false;
        if($graph !== false){
            return $graph;
        }
        $graph =  DB::getRecords();
        return $graph;

1. First, a static variable is created, then it is checked whether a value has been assigned to it, if not, then we assign it (for example, we climb into the database and get the data).
2. next. time, when we want to get the same data, we don’t go anywhere, but return the previous selection.
I have this kind of code in several places (but in the database we climb for different data), tell me how can I remove the repeating construction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rPman, 2021-07-06
@rPman

What exactly to remove? too big code?, wrap it in a function passing the variable name in the arguments:

function cache($name,$callback)
{
  static $cache = [];

  if(isset($cache[$name])) return $cache[$name];
  return $cache[$name] = $callback();
}

var_dump(cache('graph',fn()=>DB::getRecords()));

both errors in obtaining data were resolved, and invalidation (then access to cache is needed from different methods, which means it is better to arrange it as a class, or if procedurally, add a control parameter to the function)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question