[risolto] cache dell'html di output

skillsfactory

Utente Attivo
23 Nov 2012
50
0
0
Sto scrivendo una classe per gestire una cache delle pagine di un sito con un traffico elevato. L'idea è che se una pagina sia già stata "elaborata" il server piuttosto che ri-elabborarla restituisca la copia di cache. Fin qui ci siamo.

Tuttavia la cosa prevede delle eccezioni. Ad esempio se nella pagina ho un form e l'utente ne ha appena fatto il subimit, non devo restituire versioni della pagina in cache, ed anche questo è stato risolto semplicemente controllando se $_POST sia valorizzata.

Però ora mi rimane un ultimo problema abbastanza ostico e cioè, non cachare quelle parti della pagina dove per forza di cose i contenuti saranno sempre diversi, adesempio punti in cui stampo il nome dell'utente o altri dati che ad ogni richiesta saranno estremamente variabili.

Segue la classe che come vedete è abbastanza semplice e una pagina d'esempio. L'obiettivo è che il numero random, indipendentemente dalla cache, rimanga random, quindi servirebbe un qualsiasi sistema che preveda la possibilità di cachere solo parti della pagina. Consigli?

PageCache.class.php

PHP:
class PageCache 
{
	const CACHE_BASE_PATH = 'C:\xampp\htdocs\www.test.it\tmp\\';
	const CACHE_TIME      = 3600;
	
	private static $istance;
	private $HTMLBuffer;
	
	
	
	private function __construct()
	{
		ob_start();
	}
	
	
	public function __destruct()
	{
		
	}

	
	function __clone()
	{
		return false;
	}
	
	
	
	function __wakeup()
	{
		return false;
	}

	
	
	public static function getInstance()
	{
		if( is_null( self::$istance ) )
		{
			self::$istance = new self;
		}
		
		return self::$istance;
	}

	
	
	public function cacheDisplay() 
	{
		if( $this->isCachable() )
		{
			$filename = $this->cacheFile();
	
			$content = $this->get_cache_content();	
			
			if( $content )
			{
				$this->HTMLBuffer = $content;
				
				$this->printHTML();
			}
		}
	}

	
	
	public function cachePage() 
	{
		if( $this->isCachable() )
		{
			$filename = $this->cacheFile();
			
			$handle = fopen($filename, 'w+');
			
			if( $handle !== false ) 
			{
				$content = $this->getBuffer();
				
				fwrite($handle, $content); 
				fclose($handle); 
				
				$this->HTMLBuffer = $content;
				
				$this->printHTML();
			} 
		}
	}

	
	
	public function cacheRemove() 
	{
		$filename = $this->cacheFile();
		
		if( file_exists($filename) )
			return unlink($filename);
		
		return false;
	}
	
	
	
	public function cacheClean()
	{
		$DelSuccess = 0;
		$DelFail    = 0;
		
		$files      = glob(self::CACHE_BASE_PATH . '*');
		
		foreach( $files as $file )
		{
			if( is_file($file) )
			{
				if( unlink($file) )
					$DelSuccess++;
				else
					$DelFail++;
			}
			else
			{
				$DelFail++;
			}	
		}
		
		return ( ($DelSuccess > 0) && ($DelFail == 0) );
	}
	
	
	
	private function cacheExist($filename = NULL)
	{
		if( is_null($filename) )
			return false;
		
		if( !file_exists($filename) )
			return false;
	
		if( filemtime($filename) <= (time() - self::CACHE_TIME) )
			return false;
	
		return true;
	}
	
	
	
	private function isCachable()
	{
		return ( count($_POST) <= 0 );
	}
	
	
	
	private function printHTML()
	{
		if( is_null($this->HTMLBuffer) )
		{
			$this->HTMLBuffer = $this->getBuffer();
		}
	
		die($this->HTMLBuffer);
	}
	
	
	
	private function sanitizeOutput($buffer) {

	    $search  = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
	
	    $replace = array('>','<','\\1');
	
	    $buffer  = preg_replace($search, $replace, $buffer);
	
	    return $buffer;
	}
	
	
	
	private function cacheFile()
	{
		return self::CACHE_BASE_PATH . md5( $_SERVER['REQUEST_URI'] );
	}
	
	
	
	private function get_cache_content()
	{
		$filename = $this->cacheFile();
	
		if( $this->cacheExist($filename) )
		{
			return file_get_contents($filename);
		}
			
		return null;
	}
	
	
	
	private function getBuffer()
	{
		return $this->sanitizeOutput(ob_get_clean());
	}
}


Pagina test.php
PHP:
<?php 
 require_once 'PageCache.class.php';
 
 $CacheObj = PageCache::getInstance();
 
 // $CacheObj->cacheRemove();
 // $CacheObj->cacheClean();
 
 $CacheObj->cacheDisplay();

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>
    <body>

        <p>Hello world! <?</p>
        
        <form action="?" method="post">
        POST <input type="text" name="test1" value="<?php echo ( isset($_POST['test1']) ) ? $_POST['test1'] : ''; ?>">
        <input type="submit">
        </form>
        
        <form action="?" method="get">
        GET <input type="text" name="test2" value="<?php echo ( isset($_GET['test2']) ) ? $_GET['test2'] : ''; ?>">
        <input type="submit">
        </form>
        
        <p>Data elaborazione pagina: <?php echo date('d/m/Y H:i:s'); ?></p>

        <p>Random: <?php echo rand(); ?></p>

    </body>
</html>
<?php $CacheObj->cachePage(); ?>
 

skillsfactory

Utente Attivo
23 Nov 2012
50
0
0
vabbè come non detto... ho risolto da solo... posto il codice se può servire a qualcuno

PHP:
<?php
class PageCache 
{
	const CACHE_BASE_PATH = 'C:\xampp\htdocs\www.test.it\tmp\\';
	const CACHE_TIME      = 3600;
	
	private static $istance;
	private $HTMLBuffer;
	
	
	
	private function __construct()
	{
		ob_start();
	}
	
	
	public function __destruct()
	{
		
	}

	
	function __clone()
	{
		return false;
	}
	
	
	
	function __wakeup()
	{
		return false;
	}

	
	
	public static function getInstance()
	{
		if( is_null( self::$istance ) )
		{
			self::$istance = new self;
		}
		
		return self::$istance;
	}

	
	
	public function __get($property) 
	{
		if ( property_exists($this, $property) ) 
		{
			return $this->$property;
		}
		
		return null;
	}

	
	
	public function __set($property, $value) 
	{
      	$this->$property = $value;
	}
	
	
	public function cacheDisplay() 
	{
		if( $this->isCachable() )
		{
			$filename = $this->cacheFile();
	
			$content = $this->get_cache_content();	
			
			if( $content )
			{
				$this->HTMLBuffer = $content;
				
				$this->printHTML();
			}
		}
	}

	
	private function replaceVars($buffer = '')
	{
		$buffer = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/i',
		function ($matches) {
			$replace = $this->__get($matches[1]);
			return str_ireplace($matches[0], $replace, $matches[0]);
		},
		$buffer
		);
		
		
		return $buffer;
	}
	
	
	public function cachePage() 
	{
		if( $this->isCachable() )
		{
			$filename = $this->cacheFile();
			
			$handle = fopen($filename, 'w+');
			
			if( $handle !== false ) 
			{
				$content = $this->getBuffer();
				
				fwrite($handle, $content); 
				fclose($handle); 
				
				$this->HTMLBuffer = $content;
				
				$this->printHTML();
			} 
		}
                else
		{
			$this->printHTML();
		}
	}

	
	
	public function cacheRemove() 
	{
		$filename = $this->cacheFile();
		
		if( file_exists($filename) )
			return unlink($filename);
		
		return false;
	}
	
	
	
	public function cacheClean()
	{
		$DelSuccess = 0;
		$DelFail    = 0;
		
		$files      = glob(self::CACHE_BASE_PATH . '*');
		
		foreach( $files as $file )
		{
			if( is_file($file) )
			{
				if( unlink($file) )
					$DelSuccess++;
				else
					$DelFail++;
			}
			else
			{
				$DelFail++;
			}	
		}
		
		return ( ($DelSuccess > 0) && ($DelFail == 0) );
	}
	
	
	
	private function cacheExist($filename = NULL)
	{
		if( is_null($filename) )
			return false;
		
		if( !file_exists($filename) )
			return false;
	
		if( filemtime($filename) <= (time() - self::CACHE_TIME) )
			return false;
	
		return true;
	}
	
	
	
	private function isCachable()
	{
		return ( count($_POST) <= 0 );
	}
	
	
	
	private function printHTML()
	{
		if( is_null($this->HTMLBuffer) )
		{
			$this->HTMLBuffer = $this->getBuffer();
		}
	
		$this->HTMLBuffer = $this->replaceVars($this->HTMLBuffer);
		
		die($this->HTMLBuffer);
	}
	
	
	
	private function sanitizeOutput($buffer) {

	    $search  = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
	
	    $replace = array('>','<','\\1');
	
	    $buffer  = preg_replace($search, $replace, $buffer);
	
	    return $buffer;
	}
	
	
	
	private function cacheFile()
	{
		return self::CACHE_BASE_PATH . md5( $_SERVER['REQUEST_URI'] );
	}
	
	
	
	private function get_cache_content()
	{
		$filename = $this->cacheFile();
	
		if( $this->cacheExist($filename) )
		{
			return file_get_contents($filename);
		}
			
		return null;
	}
	
	
	
	private function getBuffer()
	{
		return $this->sanitizeOutput(ob_get_clean());
	}
}




PHP:
<?php 
 require_once 'PageCache.class.php';
 
 
 $CacheObj = PageCache::getInstance();
 
 //$CacheObj->cacheRemove();
 //$CacheObj->cacheClean();
 
 $CacheObj->__set('RANDOM',   rand() );
 $CacheObj->__set('USERNAME', 'User_'.rand() );

 
 $CacheObj->cacheDisplay();

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>
    <body>

        <p>Hello {$USERNAME}!</p>
        
        <form action="?" method="post">
        POST <input type="text" name="test1" value="<?php echo ( isset($_POST['test1']) ) ? $_POST['test1'] : ''; ?>">
        <input type="submit">
        </form>
        
        <form action="?" method="get">
        GET <input type="text" name="test2" value="<?php echo ( isset($_GET['test2']) ) ? $_GET['test2'] : ''; ?>">
        <input type="submit">
        </form>
        
        <p>Data elaborazione pagina: <?php echo date('d/m/Y H:i:s'); ?></p> 
        
        
        <p>Random: {$RANDOM}</p> 
        <p>User:   {$USERNAME}</p> 
        <p>NotSet:   {$NOTSET}</p> 

    </body>
</html>
<?php $CacheObj->cachePage(); ?>
 
Ultima modifica:
Discussioni simili
Autore Titolo Forum Risposte Data
R [risolto] Cache per file pdf PHP 2
L (risolto) MySQL 0
B getElementById su piu id(Risolto) Javascript 7
L Esercitarsi con Js [RISOLTO] Javascript 4
C [RISOLTO]Inserimento variabile php in input html PHP 20
L risolto visualizzazione e ordinamento dati PHP 1
moustache [RISOLTO] SQL PHP IIS PHP 8
Sergio Unia Ricezione email con destinatari multipli [Risolto] PHP 2
L update tabelle in php mysql [risolto] PHP 6
M Semplice visualizzatore di immagini [risolto con plugin wp] PHP 7
L [RISOLTO] Stampa a video risultato count in html PHP 13
L [RISOLTO] Eliminare una discussione creata PHP 3
tomorc [HTML] Problema con scroll bar (risolto) HTML e CSS 0
A [PHP] Problema query insert [RISOLTO] PHP 14
B [PHP] recuperare IP dei server in load balancing [RISOLTO] PHP 3
K [RISOLTO] Problema Griglia Php+Mysql PHP 13
S [RISOLTO] aggiorna tabella da select option asp classic Classic ASP 7
elpirata [RISOLTO][Javascript] Datapicker e autocompletamento campo input Javascript 2
elpirata [RISOLTO][Mysql] Problema insert valori apostrofati MySQL 1
elpirata [RISOLTO][Mysql] Contare le occorrenze in un campo tipo varchar MySQL 2
G [MS Access] Gestione biglietti [RISOLTO] MS Access 2
G [MS Access] Casella combinata & Query [RISOLTO] MS Access 4
G [MS Access] Query mese corrente con conteggio [RISOLTO] MS Access 2
M [RISOLTO]Windows media player non mi funziona più su win 10 pro 64 bit Windows e Software 2
C [RISOLTO][PHP] Errore di sintassi PHP 8
IT9-Gpp [RISOLTO] Leggere variabile restituita da success Ajax 3
Kolop [RISOLTO][PHP] Problema Pagination PHP 2
C [RISOLTO][PHP] Funzione ONclick PHP 14
C [RISOLTO][PHP] Conteggio righe di una tabella PHP 4
N [PHP] Utilizzo variabili di sessione [Risolto] PHP 13
Tommy03 [RISOLTO][PHP] Webserver o devserver? PHP 2
Sergio Unia Recupero dati da una vecchia versione MySql [Risolto] MySQL 4
spider81man [PHP] Problemi cancellazione dato su DB [RISOLTO] PHP 1
A [RISOLTO]Inserimento Immagini da pc a MySql PHP 15
A [PHP] RISOLTO Invio Mail con Tabella PHP 2
felino Risolto - [Wordpress][WooCommerce] PayPal Checkout e campi di fatturazione WordPress 2
elpirata [PHP][RISOLTO] Sommare gli importi estratti da un ciclo while PHP 3
elpirata [PHP][RISOLTO] Effettuare la somma dei tempi di lavorazione PHP 3
elpirata [PHP] [RISOLTO]Sovrascrivere testo in una tabella PHP 2
A [RISOLTO]Recuperare dati inviati con json tramite php PHP 4
C [RISOLTO][PHP] Passaggio variabili senza refresh di pagina PHP 7
elpirata [PHP][RISOLTO] Errore di tipo Notice: Undefined index - Come risolvere quando si hanno tante var PHP 10
S Problema in PHP per invio file XML - RISOLTO- PHP 8
A [Javascript] [RISOLTO] Doppio "submit", in uno stesso "Form" , che puntino ad "action" diversi Javascript 1
marino51 [Risolto]videochat di messenger ha smesso di funzionare sul telefonino Smartphone e tablet 1
A [Javascript] [HTML] RISOLTO...Allungare un box all'apertura della pagina No Mouse over Javascript 9
ken_korn [Javascript][Risolto] browser.tab.Tabs.favIconUrl non funziona Javascript 5
A [RISOLTO] HighChart e PHP PHP 4
A [RISOLTO] PHP Selezionare tutti i file con stessa estensione PHP 2
A [RISOLTO] Table elaborata da codice PHP con dati da DB non visualizzata in IFRAME PHP 15

Discussioni simili