我可以以某种方式全局并临时保存函数的返回数据吗?

If we have a PHP function which makes difficult calculations based on a certain input, for example:

function count_score($var1, $var2, $var3){
   // based on $var1, $var2 and $var3 we run
   // a 5000-lines long calculation,
   // resulting in one $output
   return $output;
}

Now, what happens here:

  • the function takes about 1 second to run
  • there aren't many combinations of $var1, $var2 and $var3 that might be inputted (roughly around 3000)

What I can do:

I can store the result of the function based on every combination and check whether it has been calculated before. I can store this to $_SESSION, per user, so every time the function is called, the results are looked up in the $_SESSION.

However, what if I want to store these results for all users? I can't use $_SESSION then, as it's not shared globally across the site for all users. How can I store it then?

The only time when the results of the calculations are different is when I change the function, which happens about once in 48 hours. Then I can probably manually specify the function revision and check for results of that revision. But how/where do I store all this?

EDIT Optionally, the method should work in CRON (without the http layer), but it's not necessary.

I suggest three simple solutions:

  1. APC - http://php.net/manual/en/book.apc.php
  2. Memcache - http://memcached.org/
  3. Memory (MySQL Storage Engine) - http://dev.mysql.com/doc/refman/5.5/en/memory-storage-engine.html

Memcache will automatically handle the memory available, so if you are going to store 1 byte more above the limit, memcache will delete the oldest stored value in order to "make space". APC too.

The difference between APC and Memcache is that APC doesn't need a separate installation and is not distributed, so you can't store the data on APC and get this data from a pool of servers. It be the best solution if your application runs on a single server.

With Memory, you can create a classic MySQL table which is easier to maintain and setup. Memory is about as fast as APC and Memcache, because with this Storage Engine, all the data is persisted in RAM, so if you reboot your server you are going to loose all the data stored in the table, but it is very fast and fits your needs.

In my opinion APC is the best solutions for you.

You can store the combinations in database, and look it up in it. So it is shared between users.

If the function is modified than you can erase the database.

Why not store the combinations/results in an array, json_encode() it, and write to a file. Load the file whenever you need and json_decode() it.

You can save temporary data in memcached, simply do this:

$m = new Memcached();
$m->addServer('localhost', 11211);

$key = "count_score_result_{$var1}_{$var2}_{$var3}";
$result = $m->get($key);
if(!$result){
    $result = count_score($var1,$var2,$var3);
    $result = $m->set($key,$result,15000);
}