Skip to content

Instantly share code, notes, and snippets.

@nickl-
Forked from alganet/FluentCache.php
Last active December 13, 2015 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickl-/4995970 to your computer and use it in GitHub Desktop.
Save nickl-/4995970 to your computer and use it in GitHub Desktop.
The SimpleCache interface which enables cache invalidate and exposes a single method seen to manage get, save, saveAll, and delete. Simplicity is one goal but this enables us to easily extend your Cache implementation with SimpleCacheApc, SimpleCacheMemcached, SimpleCacheRedis, SimpleCacheElasticSearch, etc. of the same SimpleCache interface.
<?php
interface SimpleCache {
function seen($key, $value=false);
function invalidate($key=false, DateTime $expire=null);
}
class FluentCache extends \ArrayObject implements SimpleCache
{
private $cache,
$lifetime = array(),
$expiry = 10000000000;
public function __construct(\Doctrine\Common\Cache\Cache $cache, array $data = array())
{
$this->cache = $cache;
parent::__construct($data, static::ARRAY_AS_PROPS);
}
public function seen($key, $value=false)
{
/** set complete collection $cache->seen($collection); */
if (is_array($key))
return $this->__invoke($key);
/** set cache value $cache->seen('abc', 123); */
if (false !== $value)
$this->offsetSet($key, $value);
/** the cache entry has expired see SimplCache::invalidate() */
if (isset($this->lifetime[$key]) && time() > $this->lifetime[$key] || time() > $this->expiry)
$this->offsetUnset($key);
return $this->offsetGet($key);
}
public function invalidate($key=false, DateTime $expire=null)
{
/** convenience wrap for $cache->invalidate(false, new DateTime) */
if ($key instanceof DateTime) {
$expire = $key;
$key = false;
}
/** return and set global expiry also $cache->invalidate();*/
if (false === $key) {
if (!is_null($expire))
$this->expiry = $expire->getTimeStamp();
return $this->expiry;
}
/** set expiry for specific key $cache->invalidate('abc', new DateTime);*/
if (!is_null($expire))
$this->lifetime[$key] = $expire->getTimeStamp();
/** return expiry for specific key */
return isset($this->lifetime[$key]) ? $this->lifetime[$key] : null;
}
public function offsetExists($id)
{
return $this->cache->contains($id);
}
public function offsetGet($id)
{
return $this->cache->fetch($id);
}
public function offsetSet($id, $data)
{
return $this->cache->save($id, $data);
}
public function offsetUnset($id)
{
return $this->cache->delete($id);
}
public function __invoke(array $data)
{
foreach ($data as $key => $value) {
$this[$key] = $value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment