Php data cache class

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple, fast, and powerful PHP Dynamic Cache Class that allows caching your dynamic web pages.

License

msbatal/PHP-Cache-Class

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

SunCache is a simple, fast, and powerful PHP dynamic cache class that uses the file system for caching.

Download all files (except Test directory), change the htaccess.txt file’s name to the .htaccess (important), and move it to your cache directory.

To utilize this class, first import SunCache.php into your project, and require it. SunCache requires PHP 5.5+ to work.

Simple initialization with default parameters:

$config = [ 'cacheDir' => 'suncache', // cache folder path 'fileExtension' => 'scf', // cache file extension 'storageTime' => 24*60*60, // cache storage time (seconds) 'excludeFiles' => ['file1.php', 'file2.php'], // exclude files from caching (with extensions) 'contentMinify' => true, // cahe content minification 'showTime' => true, // show page load time 'sefUrl' => false // website sef url status ]; $cache = new SunCache(true, $config);

All config parameters are optional.

Читайте также:  Символ пробел html код

It will use default parameters that are set in the class if you don’t specify the parameters while creating the object.

Cache files using parameters in an internal array

$cache = new SunCache(true, ['cacheDir' => 'suncache', 'fileExtension' => 'scf', 'storageTime' => 60*60, 'contentMinify' => true]);

Cache files using default parameters (set in class)

Cache files using default parameters except the time (limited time caching)

$cache = new SunCache(true, ['storageTime' => 3600]); // or 60*60 (seconds)

Caching with Minified Content

Cache files with minified content (remove all unwanted characters)

$cache = new SunCache(true, ['contentMinify' => true]);

This may cause some problems with javascript code works (if you use js codes on the same page, inline, or top/bottom of the page).

Cache files with SEF URL (if you use HTML extensions instead of PHP)

$cache = new SunCache(true, ['sefUrl' => true]);

Exclude Some Files from Caching

Exclude some specific files from caching.

$cache = new SunCache(true, ['excludeFiles' => ['file1.php', 'file2.php']]);

Don’t forget to send the file names (with php extension) in an array parameter.

This method deletes all cached files in the cache directory.

$cache = new SunCache(false, $config); $cache->emptyCache();

Don’t forget to create a new object with false parameter.

Delete a Specific Cached File

This method deletes a specific cached file in the cache directory.

$cache = new SunCache(false, $config); $cache->deleteCache('cachedFileName'); // file name (string)

Don’t forget to create a new object with false parameter.

You should send the file name (without extension) as a string parameter to the delete method.

Delete Specific Cached Files

This method deletes some specific cached files in the cache directory.

$cache = new SunCache(false, $config); $cache->deleteCache(['cachedFileName1', 'cachedFileName2', 'cachedFileName3']); // file names (array)

Don’t forget to create a new object with false parameter.

You should send all file names (without extensions) as an array parameter to the delete method. If you send filename as a file name, the class will delete all files containing filename term (ex. filename, filename1, filename_xxx, xxx_filename_yyy, etc.).

About

Simple, fast, and powerful PHP Dynamic Cache Class that allows caching your dynamic web pages.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A light, simple and powerful PHP Cache Class

License

hardik-choudhary/php-caching

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Читайте также:  Python syntaxerror non ascii characters

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A light, simple and powerful PHP Cache Class that uses the filesystem for caching. Your feedback is always welcome.

  • PHP 7.4.0 or higher (cache.class.php)
  • PHP 5.1.6 or higher (cache.class-old.php)

Basically, the caching class stores its data in files in text format. Files will be created for each cache you will create, it will use less memory (RAM) in comparison to using a single file for multiple caches.

First include the Cache class:

 require_once 'cache.class.php'; // require_once 'cache.class-old.php'; // for older versions of php // Create an instance; $cache = new Cache('cache'); // We have to pass cache directory (folder) path ?>

$classInstance->write(string $cacheName, string $content)
Params

  • $cacheName (Required): Any string that will be used to access the cache in future
  • $content (Optional): Content (as string);
 $cache->write('cache-name', 'This is the content'); ?>

$classInstance->read(string $cacheName, int $maxAge = 0, bool $deleteExpired = TRUE)
Params

  • $cacheName (Required): String that was used while creating cache
  • $maxAge (Optional): Seconds; Return NULL if file older then these seconds. Default: 0, No limit
  • $deleteExpired (Optional): TRUE OR FALSE; Delete cache if file age is more then maxAge. Default: TRUE
 $cache->read('cache-name', 200, TRUE); ?>

The cache files will be stored in a subfolder in the cache directory
$classInstance->setSubFolder(string $subFolder)
Params

 $cache->setSubFolder('ip-files'); $cache->write('134.201.250.155', ''); $ipdate = $cache->read('134.201.250.155', 200, TRUE); ?>

Delete Expired Cache files:

$classInstance->clear(int $maxAge = 0)
Params

  • $maxAge (Optional): Seconds; Return NULL if file older then these seconds. Default: 0, delete all

$classInstance->clearAll()
It will delete every thing from cache directory

Please check test folder for examples

require_once("cache.class.php"); $cache = new Cache('cache'); $page pl-s">home.php"; $cacheMaxAge = 86400; // One Day $cachedData = $cache->read($page, $cacheMaxAge); if($cachedData != NULL)< echo $cachedData; die; > else< ob_start(); include($page); $page_content = ob_get_contents(); $cache->write($page, $page_content); ob_end_flush(); >

Источник

Кэширование данных в PHP на примере класса

Заметки айтишника

Для очередного клиента разрабатывал интернет-магазин запчастей. Каталога как такового там не было, однако была куча поставщиков, подключенных через API.

Так как клиентов планировалось много, то постоянное обращение к API было бы слишком затратно для сервера.

В рамках этого проекта был написан простой класс, который позволяет кэшировать данные, полученные в ходе каких-либо операций в файл и использовать их в любое удобное время с минимальной задержкой.

 public static function checkCache($name) < // Проверка наличия элемента в кэше if(file_exists($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp'))< return true; >else < return false; >> public static function getCache($name) < // Получить элемент из кэша if(self::checkCache($name))< return unserialize(base64_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp'))); >else < return false; >> public static function writeCache($name, $arValue) < // Записать элемент в кэш if(file_put_contents($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp', base64_encode(serialize($arValue))))< return true; >else < return false; >> public static function clearCache() < // Очистить кэш foreach(scandir($_SERVER['DOCUMENT_ROOT'].self::$cache_dir) as $file)< if($file == '.' or $file == '..') continue; if(!unlink($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.$file))< return false; >> return true; > public static function delFromCache($name) < // Удалить элемент из кэша if(self::checkCache($name))< if(!unlink($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp'))< return false; >> return true; > public static function getSize($name) < // Получить размер элемента в кэше if(self::checkCache($name))< return $_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp'; >return true; > public static function getCacheSize() < // Получить размер кэша $return_size = 0; foreach(scandir($_SERVER['DOCUMENT_ROOT'].self::$cache_dir) as $file)< if($file == '.' or $file == '..') continue; $return_size = $return_size + filesize($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.$file); >return $return_size; > public static function ageOfCache($name) < // Получить возраст элемента кэша if(self::checkCache($name))< return (time() - filectime($_SERVER['DOCUMENT_ROOT'].self::$cache_dir.md5($name).'.tmp')); >else < return false; >> > ?>

Несмотря на малое количество строк кода, он с легкость решает поставленную задачу, а именно:

  • Проверка наличия кэша элемента
  • Получение элемента из кэша
  • Запись элемента в кэш
  • Удаление элемента из кэша
  • Очистку кэша
  • Получение размера кэша
  • Получение размера конкретного элемента в кэше

Все методы класса являются статическими, поэтому создавать экземпляр класса не требуется.

Ниже я приведу полное описание всех доступных методов.

CCache::init(‘/folder/’);

Установка дирректории для хранения кэша. Указывать со слешами в начале и в конце.

CCache::checkCache($name);

Выполняет проверку наличия кэша в базе. Принимает в качестве аргумента идентификатор элемента $name. Если элемент присутствует в кэше — вернет true, иначе — false.

CCache::getCache($name);

Получает элемент из кэша, возвращает массив. Если элемент в кэше не найден — вернет false.

CCache::writeCache($name, $arValue);

Запись данных в кэш. Принимает два аргумента: имя элемента $name и данные $arValue. В свою очередь данные $arValue должны являться массивом. При наличии элемента в кэше он будет перезаписан.

CCache::clearCache();

Метод полностью очищает кэш. Вернет false в случае ошибки.

CCache::delFromCache($name);

Метод удаляет конкретный элемент из кэша, принимает имя элемента $name в качестве аргумента. Вернет false в сллучае ошибки удаления.

CCache::getSize($name)

Метод возвращает размер элемента $name в байтах. Если элемент в кэше не найден — вернет false.

CCache::getSize($name)

Метод возвращает размер кэша в байтах

Источник

Оцените статью