Skip to content

Instantly share code, notes, and snippets.

@azeredogab
Created May 25, 2017 21:18
Show Gist options
  • Save azeredogab/75b13e6adee1baebeda242258b9310fa to your computer and use it in GitHub Desktop.
Save azeredogab/75b13e6adee1baebeda242258b9310fa to your computer and use it in GitHub Desktop.
Classe criada para fazer um file cache de dados para aplicações PHP
<?php
/**
* Classe com o objetivo de criar um file cache simples para guardar dados de consulta sql
* Mode de Uso:
*
* - Primeiro configure os atributos no inicio da classe com os valores desejados:
* - $_default_path - Pasta onde o cache será salvo
* - $_cache_timeout - Tempo de duração do cache em horas
* - $_cache_type - Extensão do arquivo de cache
*
* - Agora, para instanciar no seu script php, utilize da seguinte forma:
*
* //obtenha o caminho do cache
* $cache_path = Cache::getCachePath();
*
* if (!Model\Cache::isExpired($cache_path, 'nome_do_arquivo_de_cache_sem_extensão')){
* $data = Cache::getCache($cache_path, 'nome_do_arquivo_de_cache_sem_extensão');
* } else {
* $data = Consulta::findData($id); // faz a consulta original
* Cache::setCache($cache_path, 'nome_do_arquivo_de_cache_sem_extensão', $data);
* }
*
* //variável $data contém seus dados.
*/
//namespace Model;
class Cache {
public static $_default_path = "temp/";
public static $_cache_timeout = "4"; //em horas
public static $_cache_type = ".txt";
//não permite instâncias dessa classe
private function __construct(){}
public static function getCache($cache_path, $cache_id)
{
$cache_file = $cache_path.$cache_id.self::$_cache_type;
if (file_exists($cache_file)){
$content = file_get_contents($cache_file);
$content = unserialize($content);
return $content;
} else
return false;
}
public static function setCache($cache_path, $cache_id, $body)
{
$cache_file = $cache_path.$cache_id.self::$_cache_type;
/**
* No caso desse framework, não conseguimos utilizar o json_encode, pois ele não consegue tradutor um array de objetos, então,
* precisamos usar outro comando, chamado serialize e unserialize para transformar o objeto em string e salvar o cache.
*/
$body = serialize($body);
try {
$file_opened = fopen($cache_file, 'a+');
fwrite($file_opened, $body);
fclose($file_opened);
} catch (Exception $e) {
return false;
}
return true;
}
public static function isExpired($cache_path, $cache_id)
{
return file_exists($cache_path.$cache_id.self::$_cache_type) ? false : true;
}
public static function getCachePath()
{
//remove os diretórios que não estão dentro do timeout
$dir = new \DirectoryIterator(self::$_default_path);
$current_dir = "";
$return = false;
foreach($dir as $file) {
if (!$dir->isDot() && $dir->isDir()) {
$dir_name = $file->getFilename();
$time = explode('_', $dir_name);
$time[1] = str_replace('-', ':', $time[1]);
$limit_datetime = implode(' ', $time);
$data1 = $limit_datetime;
//$data1 = date('2017-01-23 15:06:00');
$data2 = date('Y-m-d H:i:s');
$unix_data1 = strtotime($data1);
$unix_data2 = strtotime($data2);
$intervalo = ($unix_data2 - $unix_data1) / 3600;
if (intval($intervalo) > self::$_cache_timeout) {
self::removeDirectory(self::$_default_path.$dir_name);
} else {
$current_dir = self::$_default_path.$dir_name."/";
}
}
}
if (empty($current_dir)) {
$t = date('Y-m-d_H-i-s');
mkdir(self::$_default_path.$t."/", 0777);
$current_dir = self::$_default_path.$t."/";
}
return $current_dir;
}
public static function removeDirectory($path)
{
$files = glob($path . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment