Vi propongo un sistema di caching che mi sono fatto per un mio cms.

La logica è abbastanza semplice, genero un hash dell'url tramite md5 per riconoscere in modo univoco il file contenente l'output di questa richiesta.

Nel file ci salvo un array, che contiene il contenuto della risposta e gli headers.

Ovviamente la directory cache deve esistere ed essere scrivibile dall'user con cui gira apache.

Ecco il codice:

Cache.class.php
Codice PHP:
<?php
class cache {

    private 
$path;
    private 
$time_expire;
    private 
$token;

    function 
__construct($token) {

        
$this->time_expire 120;
        
$this->token md5($token);
        
$this->path realpath("./cache") . "/";
    }

    function 
read_cache() {
        if (
file_exists($this->path $this->token)) {
            if ((
time() - filemtime($this->path $this->token)) <= $this->time_expire) {
                
                
$filename=$this->path $this->token;
                
$handle fopen($filename"r");
                
$contents fread($handlefilesize($filename));
                
fclose($handle);
                
                
$result=unserialize($contents);
                
                for(
$i=0;$i<sizeof($result["HEADERS"]);$i++){
                    
header($result["HEADERS"][$i]);
                }
                
                echo 
$result["CONTENT"];

                return 
true;
            } else {
                return 
false;
            }
        } else {
            return 
false;
        }
    }

    function 
save_cache() {

        
$result=array();
        
$result["CONTENT"] = ob_get_contents();
        
$result["HEADERS"] = headers_list();
        
        
$data=serialize($result);

        if (
strlen($result["CONTENT"]) > 0) {
            
$filename $this->path $this->token;

            if (!
$handle fopen($filename'w+')) {
                echo 
"Non si riesce ad aprire il file ($filename)";
            }

            if (
fwrite($handle$data) == false) {
                echo 
"Non si riesce a scrivere nel file ($filename)";
            }

            
fclose($handle);
        }
    }


}
ed ecco come si usa:

Index.php
Codice PHP:
<?php
session_start
();
ob_start();

require_once(
"Cache.class.php");
$cache = new Cache($_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);

if (
$cache->read_cache()) {

} else {
/*
qui il mio cms stampa n cose possibili in base al template e al modulo richiesto
*/
$cache->save_cache();
}
?>