Petit système de cache

ViPHP
fab
ViPHP | 2657 Messages

12 mai 2005, 21:20

Voici un très simple systeme de cache facile à utiliser et facilement intégrable dans un application.
Merci a calimero pour le code de départ

Attention : il faut avoir un sous-dossier cache/ du répertoire courant,
<?php
/*
File: function.cache.php
Liscence : GPL
Author : [email protected]
*/
function cache_exists($path){ // Test si un cache existe ou non pour ce paramètre
	return (is_file('cache/'.md5($path).'.txt'));
}
function cache_time($path) {
	clearstatcache();
	return (filemtime('cache/'.md5($path).'.txt'));
}
function cacheresult ($path, &$data){ // Ecriture du fichier cache pour ce paramètre
	_file_put_contents('cache/'.md5($path).'.txt',serialize($data));
}
function &getcache ($path){ // Lecture du fichier cache pour ce paramètre
	return unserialize(file_get_contents('cache/'.md5($path).'.txt'));
}
function cache_destroy($path) {
	unlink('cache/'.md5($path).'.txt');
}
function _file_put_contents($filename, $data, $file_append = false) {
	$fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
	if(!$fp) {
		trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
		return;
	}
	fputs($fp, $data);
	fclose($fp);
}

?>
Et maintenant voici un exemple simple d'utilisation :
<?php
$generation = FALSE;
if(cache_exists("total_irc")) { // vérification de l'éxistence de fichier de cache
	$time_cache = time() - cache_time("total_irc");
	if($time_cache > 600) { // fichier généré y a plus de 600 secondes ?
		$generation = TRUE; // on demande la génération
	}
	else { // le temps est ok
		$users_total = getcache("total_irc"); // récupération du cache
		$generation = FALSE; // pas de génération
	}
}
else { // le fichier cache n'éxiste pas
	$generation = TRUE; // on demande la génération
}
if($generation == TRUE) {
	$bot = new BotConnexion() ; // faites pas attention a la class c'est pour l'exemple
	if($bot->connect()) { // connexion ok ?
		cache_destroy("total_irc"); // destruction du cache, maintenant qu'on est sur de la génération
		$users_total = $bot->connexions();
		cacheresult("total_irc",$users_total); // on insere ce qu'on veut dans le cache
	}
	else { // pas de connexion on récupère le cache
		$users_total = getcache("total_irc"); // récupération de l'ancien cache
	}
}
?>