Simple cache classes

v0.0.2 2019-03-30 13:04 UTC

README

Build Status Code Coverage Latest Stable Version License

This is a simple cache library. It exposes several different caching mechanisms (with different semantics) under a common interface. Nothing fancy.

Interface

The cache interface exposes get and set methods, which do exactly what you'd expect from a cache:

// PHPCache is a trivial array-backed cache.
$cache = new \Vectorface\Cache\PHPCache();
$cache->get("foo"); // false, because we just created this cache.
$cache->set("foo", "bar"); // returns true if set. This cache always succeeds.
$cache->get("foo"); // "bar", because we just set it.

The interface supports optional time-to-live (expiry) where supported by the underlying cache type. The interface also provides delete, clean, and flush methods to delete one entry, all expired entries, and all entries (respectively).

Available Implementations

  • APCCache: APC or APCu.
  • MCCache: Memcache
  • NullCache: A blackhole for your data
  • PHPCache: Stores values in a local variable, for one script execution only.
  • SQLCache: Values stored in an SQL table, accessed via PDO.
  • TempFileCache: Store values in temporary files.
  • TieredCache: Layer any of the above caches on top of each other to form a hybrid cache.

Real-World Use

Why would you want to use this? It makes it almost trivial to switch your underlying cache implementation without any code changes. This can be especially useful for testing.

use Vectorface\Cache\APCCache;
use Vectorface\Cache\PHPCache;
use Vectorface\Cache\TempFileCache;
// Memcache and SQL-based caches also work, but aren't as good as examples.

$caches = [new APCCache(), new PHPCache(), new TempFileCache()];
foreach ($caches as $cache) {
	// Look ma! Same interface!
	$cache->set('foo', 'bar');
	$cache->get('foo');
}

Tiered Caching

Another particularly useful feature is the ability to stack caches. You can put fast caches in front of successively slower caches, presumably where the fast caches will have less storage and evict items used less often.

use Vectorface\Cache\APCCache;
use Vectorface\Cache\MCCache;
use Vectorface\Cache\TempFileCache;
use Vectorface\Cache\TieredCache;

$memcache = new Memcache();
$memcache->addServer("127.0.0.1");
$cache = new TieredCache([
	new APCCache(),
	$memcache,
	new TempFileCache(),
]);

$cache->get("foo"); // Tries all caches in sequence until one succeeds. Fails if none succeed.
$cache->set("foo", "bar"); // Sets a value in all caches.
$cache->set("foo"); // Tries all caches in sequence. The fastest should succeed and return quickly.