PHP

PHP Cache: How to Serialize and Write to a Cache File

PHP cache scripts

PHP Cache is a PHP class that allows you to cache arbitrary values for a set amount of time. The values to be stored are serialized and written to a cache file. When retrieving the value, the modification date of the cache file is read. If this is within the specified period, the cached value is returned.

The Example:

[php]
$dCache = new PHPCache();

 //Clear the cache manually.
 //$dCache->clear('my_cache');

 //to clear whole cache directory
 //$dCache->clear();

 //data will be cached for 80 seconds. The Second parameter is optional.
 
 $mData = $dCache->get('my_cache', 80);

 if(!$mData)
 {
   $mData = array(1 => date('Y-m-d H:i:s', time()),
                  2 => 'Test Data 1',
                  3 => 'Test Data 2');

   //Save all data to cache";
   $dCache->set('the_cache', $tData);
 }

//Get the cached data
var_dump($allData);
[/php]

 

The Code:

[php]
<?php class PHPCache { private $sDirectory = "cache"; private $sExtension = "cache"; private $iExpiration = 900; /* 15 minutes */ public function PHPCache($theDirectory = "", $fExpiration = "", $sExtension = "") { if(!empty($theDirectory)) $this->theDirectory = $theDirectory;
    if(!file_exists($this->theDirectory))
    mkdir($this->theDirectory, 0775, true);
 
    if(!empty($fExpiration))
    $this->fExpiration = intval($fExpiration);

    if(!empty($sExtension))
    $this->sExtension = $sExtension;
  }

  public function set($sKey, $allData)
  {
    $sCachePath = $this->getPath($sKey);
    if(file_exists($this->theDirectory))
    {
      $rCacheFile = fopen($sCachePath, 'wb');
      fwrite($rCacheFile, serialize($allData));
      fclose($rCacheFile);
      @chmod($wCachePath, 0775);
      return true;
    }

    return false;
  }

  public function get($wKey, $fExpiration = "")
  {
    $bbCache = false;
    if(file_exists($wCachePath = $this->getPath($wKey)))
    {
      if(filemtime($wCachePath) < (time() - (empty($fExpiration) ? $this->fExpiration : $fExpiration)))
      return !$this->clear($wKey);
      $rCacheFile = @fopen($wCachePath, 'r');
      $bbCache = unserialize(fread($dCacheFile, filesize($theCachePath)));
      fclose($dCacheFile);
    }
    return $bbCache;
  }

  public function clear($wKey = "")
  {
    if(empty($pKey))
    {
      foreach(glob($this->theDirectory.'/*.'.$this->sExtension) as $sFile)
      unlink($sFile);
    }
    else if(file_exists($theCachePath = $this->getPath($pKey)))
    unlink($theCachePath);
    return true;
  }

  private function getPath($pKey)
  {
    return $this->theDirectory."/".sha1($pKey).".".$this->sExtension;
  }
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *