A veces nuestro servidor se ve extensamente sobrecargado por nuestras aplicaciones. A lo que nos preguntamos, ¿qué es lo que consume tanto?; la respuesta es muchas cosas. Pero más básicamente se basa en peticiones a la base de datos.Entonces reformulemos la pregunta, ¿para qué hacer una petición a la base de datos de algo que posiblemente sea siempre igual, si podemos almacenarlo como un archivo y mostrarlo rápida, eficientemente y sin mayor consumo, en lugar de lo anterior?La respuesta a esto se llama CACHÉ, y he aquí una pequeña clase para manipular esta maravilla:


<?php
class Cache 
{
  private static $cache_dir = null;
  private static $cache_reset_field = "mab";
  private $cache_field = array();
  /** * @var {integer} 900 segundos -> 15 minutos.- */


  private $cache_time = 900;
  private $cache_file = null;


  public function __construct () 
  {
    if ( ! self::$cache_dir ) {
$this->set_cache_dir ( getcwd ()"/cached/" );
    }
  }
    

/** * @param {string} $dir.- * @return Cache.- */
  public function set_cache_dir $dir ) 
  {
    if ( ! is_dir$dir ) )
      @mkdir ( $dir, 0777 );
    self::$cache_dir = $dir;
    return $this;
  }
     

  /** * @param {string} $field.- * @return Cache.- */
  public function set_cache_reset_field ( $field 
  {
    self::$cache_reset_field = $field;
    return $this;
  }
     

  /** * @param {string} $field.- * @param {string} $value.- * @return Cache.- */

  public function add_cache_field ( $field$value ) 
  {
    $this->cache_field [] = "{$field}={$value}";
    return $this;
  }
     

  /** * @return {string}.- */
  public function get_cache_field () 
  {
    return @implode ( "&"$this->cache_field );
  }
   
  
/**
* @param {integer} $time.- * @return Cache.- */
  public function set_cache_time ( $time ) 
  {
    $this->cache_time = $time;
    return $this;  } /** * @return {integer}.- */
  public function sget_cache_time () 
  {
    return $this->cache_time;
  }
     

  /** * @return {boolean}.- */
  public function start_cache ( $cache_id = null
  { /**
* #Resetea todo el caché si es necesario.- */
    if ( isset$_GET [ self::$cache_reset_field ] ) ) { /** * #Resetea el tiempo.- */
      $this->set_cache_time ( 0 ); /** * #Archivo entero.- */
      if ( ! $cache_id ) {
        /**
* #Resetea el string.- */
        $reset_field = self::$cache_reset_field. "{ $_GET [ self :: $cache_reset_field ] }";
        $_SERVER [ "QUERY_STRING" ] = preg_replace (
            array (
              
"/&{$reset_field}/",
              "/&{$reset_field}/",
              
"/&{$reset_field}/" 
            ),
            array( ""
, "", "" ),
            $_SERVER [ "QUERY_STRING" ] );
      }
    } /**
* #Setemos el path completo.- */
    $this->cache_file = self::$cache_dir.
                              md5 ( ( 
$cache_id
                                        ? 
$cache_id
                                        : 
$_SERVER [ "SCRIPT_NAME" ].
$_SERVER [ "QUERY_STRING" ]                                    ). $this->get_cache_field()                               ); /** * #¿Existe el archivo?.- * #Si es verdadero, comienza el caché.- */ 
  if ( @file_exists$this->cache_file ) && (       ( time() - $this->get_cache_time() ) < @filemtime$this->cache_file ) ) )
   
{
      print file_get_contents$this->cache_file );          /** * #Si es un archivo(...).- */
      if ( ! $cache_id ) {
        exit;
     
}

    } 
    else {
       
/**
* #Comienza el flujo de datos (...) [ BUFFERING ].- */
      ob_start();
      return true;
    }
  }

  public function end_cache () 
  {
    /** * #Obtiene salida de datos (...) [ BUFFERING ].- */
    $cache_content = ob_get_clean ();
    $cache_file = @fopen$this->cache_file"w" );
    @fwrite$cache_file$cache_content );
    @fclose$cache_file );
/** * #Salen los datos (...).- */
    print $cache_content;
  }
}

Entonces, para usarlo, solo debemos hacer lo siguiente: creamos en la carpeta raíz del servidor un subdirectorio llamado "cached". Localizamos el archivo al cuál queremos darle el caché y agregamos dentro de el lo siguiente:

$path = $_SERVER ['DOCUMENT_ROOT'];
require_once $path.'/mi_directorio/Cache.php';

$Cached = new Cache; $Cached->start_cache(); (...)Código de la página en cuestión(...) $Cached->end_cache();

Y listo, eso fue todo por hoy. Espero que disfruten esta pequeña pero excelente clase, para que, tal vez, puedan añadirla a su repositorio y usarla cuando deseen. Ah (...), este objeto es EXCELENTE cuando se usa con PDO y el mismo se conecte mediante Singleton.

Posted in

Leave a Reply

GroovieDev, compartiendo conocimiento. Con la tecnología de Blogger.