A simple PHP class for caching data in the filesystem.


Keywords
php, file, cache, files, simple-cache, psr-16
License
MIT

Documentation

Cache

PHP Support PHP Support License Travis

Introduction

aphp/cache simple PHP class for caching.

Installation

composer require aphp/cache ~1.0.17

Hello world

require __DIR__ . '/../vendor/autoload.php';

use aphp\Cache\Cache;

@mkdir(__DIR__ . '/cache', 0777);

$cache = new Cache(__DIR__ . '/cache');

$cache->set('key1', 'data');
$data = $cache->get('key1');

$class = new StdClass();
$cache->set('key2', $class);
$classData = $cache->get('key2');

print_r($data);
echo PHP_EOL;
print_r($classData);

/* data
stdClass Object
(
) */

Features

  • PSR-16
  • Cache in files
  • Strings stored as strings
  • Classes or Arrays stored as serialized()
  • Timeout to data access stored as filemtime()
  • Can used as folder for raw files.
  • Can use the database table as cache storage (see class XPDOCache).

Syntax

Init

use aphp\Cache\Cache;
// cache dir must be exists
$cache = new Cache(__DIR__ . '/cache');

Main functions

Main functions use the PSR-16 interface to access the cache.

Syntax PSR-16

public function get($key, $default = null);
public function set($key, $data, $ttl = null);
public function delete($key);
public function clear();
public function getMultiple($keys, $default = null);
public function setMultiple($values, $ttl = null);
public function deleteMultiple($keys);
public function has($key);

Syntax FileInterface

interface FileInterface
{
	const TimeUnlimit = 0; // used for setting $tll - cache will be forever storage
	public $extension = '.cache';

	public function filenameForKey($key); // file path
	public function getFilenameForKey($key, $default = null); // file path OR null
	public function getCachePath();
	public function setExtension($ext);
	public function touch($key, $ttl = null);
}

class Cache implements \Psr\SimpleCache\CacheInterface, FileInterface
{
	public $defaultTTL = 600; // 10 minutes
	public $serialization = true;
	public $keyHashing = true;
	public $keyHashingForHumans = false;
	public $gc = 100;

	static function human_hash($key);

	public function hashKey($key);
	public function clearOldFiles($forced = true);
}

FileInterface is used to store raw files in cache, and get cache features, like:

  • time management
  • clear folder
  • clear only old files
  • filename generation

Example usage with copy

@mkdir( __DIR__ . '/cache' , 0777);
$cache = new Cache(__DIR__ . '/cache');

$sourceFile = __DIR__ . '/php.jpg';

$f1 = $cache->filenameForKey('f1');
copy($sourceFile, $f1); // user function to write file to destination
$cache->touch('f1', 3600); // set time in cache 1h

// read file
$f1 = $cache->getFilenameForKey('f1'); // file path OR null
if ($f1) {
	echo filesize($f1);
} else {
	echo 'file not exists';
}

Example usage with imagejpeg

Encryption

To encrypt cache use secureKey api:

class Cache {
    public $secureKey = null; // key for encryption
    public $secureEncryptFn = null; // function($data, $key):data
    public $secureDecryptFn = null; // function($data, $key):data, false if failed
}

Example with aphp\crypt

$cache->secureKey = 'sampleKey';
$cache->secureEncryptFn = function ($data, $key) {
    return AESEncryption::encrypt($data, $key);
};
$cache->secureDecryptFn = function ($raw, $key) {
    $data = AESEncryption::decrypt($raw, $key);
    if ($data === false) { // error detection
        return false;
    }
    return $data;
};

Garbage collector

This functions used for gc

class Cache {
	public $gc = 100;
	public function clearOldFiles($forced = true);
}
//
$cache->clearOldFiles(false); // run gc for random 1/100

Storage

Storage used to manage multiple caches.

class Storage {
	public function __construct($storagePath);
	public function getCache($name); // Cache
}
//
$cache1 = $storage->getCache('cache1');
$cache2 = $storage->getCache('cache2');

Cache in database

For use cache in database:

  • Create XPDOStorage instance.
  • Get XPDOCache from XPDOStorage::getCache($name).
  • Cache table will create automatically, if not exists.
use aphp\Cache\XPDOStorage;
use aphp\XPDO\Database;

$db = new Database;
$db->SQLiteInit(realpath(__DIR__ . '/sqlite_cache.sqlite'));

$storage = new XPDOStorage('cache_table', $db);

$cache = $storage->getCache('exampleCache');

$cache->set('key1', 'data');
$data = $cache->get('key1');
// ...

Test running

  • install phpunit, composer, php if not installed
  • run composer install at package dir
  • run composer test
🔵 Useful links

More features

For more features:

  • Read source code and examples
  • Practice with Cache in real code