Add abstract cache layer

This commit is contained in:
Frederic Guillot
2015-09-20 12:38:35 -04:00
parent 8079b5af64
commit fe57edd9e8
10 changed files with 383 additions and 93 deletions

38
app/Core/Cache/Base.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
namespace Core\Cache;
/**
* Base class for cache drivers
*
* @package cache
* @author Frederic Guillot
*/
abstract class Base
{
/**
* Proxy cache
*
* Note: Arguments must be scalar types
*
* @access public
* @param string $class Class instance
* @param string $method Container method
* @return mixed
*/
public function proxy($class, $method)
{
$args = func_get_args();
array_shift($args);
$key = 'proxy:'.get_class($class).':'.implode(':', $args);
$result = $this->get($key);
if ($result === null) {
$result = call_user_func_array(array($class, $method), array_splice($args, 1));
$this->set($key, $result);
}
return $result;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Core\Cache;
/**
* Cache Interface
*
* @package cache
* @author Frederic Guillot
*/
interface CacheInterface
{
/**
* Save a new value in the cache
*
* @access public
* @param string $key
* @param string $value
*/
public function set($key, $value);
/**
* Fetch value from cache
*
* @access public
* @param string $key
* @return mixed Null when not found, cached value otherwise
*/
public function get($key);
/**
* Clear all cache
*
* @access public
*/
public function flush();
/**
* Remove cached value
*
* @access public
* @param string $key
*/
public function remove($key);
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Core\Cache;
/**
* Memory Cache
*
* @package cache
* @author Frederic Guillot
*/
class MemoryCache extends Base implements CacheInterface
{
/**
* Container
*
* @access private
* @var array
*/
private $storage = array();
/**
* Save a new value in the cache
*
* @access public
* @param string $key
* @param string $value
*/
public function set($key, $value)
{
$this->storage[$key] = $value;
}
/**
* Fetch value from cache
*
* @access public
* @param string $key
* @return mixed Null when not found, cached value otherwise
*/
public function get($key)
{
return isset($this->storage[$key]) ? $this->storage[$key] : null;
}
/**
* Clear all cache
*
* @access public
*/
public function flush()
{
$this->storage = array();
}
/**
* Remove cached value
*
* @access public
* @param string $key
*/
public function remove($key)
{
unset($this->storage[$key]);
}
}