Blog de informática: programación, internet, php, wordpress, zend framework, mysql, windows, mootools, linux,…
In: php
15 mar 2010En el blog php-html.net, encuentro un artículo con la construcción de un script simple para cachear. Como un diccionario, una vez establecido que son las claves y cuales serán sus valores, aolamente hacen falta tres funciones:
Esta hecho en una clase que tiene dos atributos: el directorio donde se almacenará la cache, y los segundos del periodo de duración de la cache. Dejo el código php:
<?php class SimpleCache { private $cacheDir = 'cache'; private $expiryInterval = 2592000; //30*24*60*60; public function setCacheDir($val) { $this->cacheDir = $val; } public function setExpiryInterval($val) { $this->expiryInterval = $val; } public function exists($key) { $filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename $filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info if (file_exists($filename_cache) && file_exists($filename_info)) { $cache_time = file_get_contents ($filename_info) + (int)$this->expiryInterval; //Last update time of the cache file $time = time(); //Current Time $expiry_time = (int)$time; //Expiry time for the cache if ((int)$cache_time >= (int)$expiry_time) //Compare last updated and current time { return true; } } return false; } public function get($key) { $filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename $filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info if (file_exists($filename_cache) && file_exists($filename_info)) { $cache_time = file_get_contents ($filename_info) + (int)$this->expiryInterval; //Last update time of the cache file $time = time(); //Current Time $expiry_time = (int)$time; //Expiry time for the cache if ((int)$cache_time >= (int)$expiry_time) //Compare last updated and current time { return file_get_contents ($filename_cache); //Get contents from file } } return null; } public function put($key, $content) { $time = time(); //Current Time if (! file_exists($this->cacheDir)) mkdir($this->cacheDir); $filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename $filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info file_put_contents ($filename_cache , $content); // save the content file_put_contents ($filename_info , $time); // save the time of last cache update } }
Se puede utilizar de diversas maneras. La manera como lo he implementado para cachear páginas web o URLs es:
<?php require_once "SimpleCache.php"; if (isset($_GET['url'])) { $cache = new SimpleCache(); $url = $_GET['url']; $key = md5($url); if ( !$cache->exists($key)) { $value = file_get_contents($url); if ($value !== null) { $cache->put($key, $value); } else { exit(); } } echo $cache->get($key); }
Entradas relacionadas:
Este blog informático pretende ser un blog de notas o portafolio de información variada: trozos de código, descubrimientos, notas sueltas, ... Para tenerla a mano, y ser compartida.