Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Last active August 29, 2015 14:11
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 mnapoli/ce79980016cd2bffab4f to your computer and use it in GitHub Desktop.
Save mnapoli/ce79980016cd2bffab4f to your computer and use it in GitHub Desktop.
<?php
interface Cache
{
public function get($id);
public function set($id, $value);
}
<?php
class EagerCache implements Cache
{
private $values = array();
private $storage;
private $storageId;
private $isDirty = false;
public function __construct(Backend $storage, $storageId)
{
$this->storage = $storage;
$this->storageId = $storageId;
$content = $storage->doFetch($storageId);
if (is_array($content)) {
$this->values = $content;
}
}
public function get($id)
{
return $this->values[$id];
}
public function set($id, $value)
{
$this->values[$id] = $value;
}
// or could be done with a TerminableCache like Symfony's Terminable kernel
public function __destruct()
{
if ($this->isDirty) {
$this->storage->doSave($this->storageId, $this->content, $ttl);
}
}
}
<?php
class TransientCache implements Cache
{
private $values = array();
public function get($id)
{
return $this->values[$id];
}
public function set($id, $value)
{
$this->values[$id] = $value;
}
}
<?php
class TtlCache implements Cache
{
private $ttl;
private $backend;
public function __construct(Backend $backend, $ttl)
{
$this->backend = $backend;
$this->ttl = $ttl;
}
public function get($id)
{
return $this->backend->get($id, $ttl);
}
public function set($id, $value)
{
$this->backend->set($id, $value, $ttl)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment