Archive

Archives pour 11/2009

How to cache easily the result of a PHP function

Here is a little PHP function allowing to put easily in cache what an other function returns in order to avoid to call it each time. This allows to optimize a lot the execution time of the scripts when they are based on long processing.

To use it, you just have to include the code of the file lib_cache (http://www.cybwarrior.com/?file_id=73) and call the cache function in the following way:

function pause($a)
{
sleep($a);

return ’stop’;
}

print cache(3600 * 24, ‘pause’, array(10));

The first argument represents the frequency (more exactly the period :-) ) in seconds with which execute the function – in our case, every day.

The second argument is the function name. But it’s also possible to give the method of an object: this is very flexible. The feature relies on the call_user_func_array function. Report to the documentation for more information.

The third argument is the array with the arguments to give to the function, the first elements containing the first argument, and so forth.

A fourth optional argument may be added, which have to be a conjunction of the constants CACHE_REFRESH and CACHE_NO_REFRESH, which respectively forces the refresh of the cache or to the contrary returns the content even if it’s expired.

The result: in our case, the function takes 10 seconds to execute. But called with the cache function, it’s actually fully executed only one time a day, and the rest of the time, the result of the function which is in the cache is returned.

http://www.cybwarrior.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: PHP Cache (1.68KB)
added: 08/10/2009
clicks: 1062
description: Une fonction très utile pour mettre en cache le résultat d'une fonction PHP, afin d'optimiser son code et le rendre plus rapide en ne l'appelant à chaque fois. A very useful function which store in a cache file what an other function returns, in order to optimize the code and make it quicker.

Categories: PHP Tags: ,