Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Bom segue ai um sistema para pegar conteudo do DB e salvar em um arquivo estatico um cache no servidor!!!
Tmb quero sugestões sobre esse script se realmente ele alivia alguma coisa =X
<?php
class Cache{
protected $folter;
protected $timeout;
protected static $content;
protected $ext;
public function __construct($timeout=60, $folter='cache', $ext='txt') {
$this->timeout = $timeout;
$this->folter = $folter;
$this->ext = $ext;
}
public function getPathFileName($key) {
return sprintf('%s/%s.%s', $this->folter, md5($key), $this->ext);
}
private function exist($filename) {
return file_exists($filename);
}
public function isCache($key) {
$filename = $this->getPathFileName($key);
if (!$this->exist($filename)) {
return true;
}
$filetime = filemtime($filename);
if (time() > $filetime + ( 60 * $this->timeout )) {
return true;
}
return false;
}
public function cacheOutputtoFile() {
self::$content = strtr(ob_get_contents(),
array("\t" => '', "\n" => '', "\r" => ''));
return ob_end_clean();
}
public function write($key) {
$filename = $this->getPathFileName($key);
if (!file_put_contents($filename, self::$content)) {
throw new Exception('Não foi possivel gravar no Arquivo ' . $key);
}
}
public function read($key) {
$filename = $this->getPathFileName($key);
if ($this->exist($filename)) {
if (!$result = file_get_contents($filename)) {
throw new Exception('Não foi possivel Ler Arquivo ' . $key);
}
return $result;
}
}
}
Usando :
try {
$result = mysql_query("SELECT * FROM Persons");// seu select
$data = mysql_fetch_assoc($result);
ob_start();// armazenando os dados no buffer (Resultado do foreach)
$cache = new Cache(60, 'cache', 'html');// tempo, Pasta, formato do arquivo
// ('cache') faz referencia ao nome do arquivo criado-- pode ser uma variavel dinamica
if ($cache->isCache('cache')) {
echo '<div id="main_text">';
foreach ($data as $texto) {
echo $texto['textNoticia'], '....';// conteudo do DB
}
}
echo '</div>';
$cache->cacheOutputtoFile();// exibindo os dados do buffer
$cache->write('cache');// escrevendo dados
}
echo $cache->read('cache'); //exibindo conteudo do arquivo
} catch (Exception $e) {
$content = 'Error: ' . $e->getMessage();
}Carregando comentários...