Skip to content

Commit

Permalink
Add Cache::remember()
Browse files Browse the repository at this point in the history
This method provides a really simple approach to read-through caching.
A callable or Closure can be used to provide results when the cache is
empty.
  • Loading branch information
markstory committed Oct 5, 2013
1 parent 5e9b222 commit f146d43
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/Cake/Cache/Cache.php
Expand Up @@ -542,4 +542,27 @@ public static function groupConfigs($group = null) {
throw new CacheException(__d('cake_dev', 'Invalid cache group %s', $group));
}

/**
* Provides the ability to easily do read-through caching.
*
* When called if the $key is not set in $config, the $callable function
* will be invoked. The results will then be stored into the cache config
* at key.
*
* @param string $key The cache key to read/store data at.
* @param callable $callable The callable that provides data in the case when
* the cache key is empty.
* @param string $config The cache configuration to use for this operation.
* Defaults to default.
*/
public static function remember($key, $callable, $config = 'default') {
$existing = self::read($key, $config);
if ($existing !== false) {
return $existing;
}
$results = call_user_func($callable);
self::write($key, $results, $config);
return $results;
}

}
26 changes: 26 additions & 0 deletions lib/Cake/Test/Case/Cache/CacheTest.php
Expand Up @@ -27,6 +27,8 @@
*/
class CacheTest extends CakeTestCase {

protected $_count = 0;

/**
* setUp method
*
Expand Down Expand Up @@ -491,4 +493,28 @@ public function testSetOnAlternateConfigs() {
$this->assertEquals('test_file_', $settings['prefix']);
$this->assertEquals(strtotime('+1 year') - time(), $settings['duration']);
}

/**
* test remember method.
*
* @return void
*/
public function testRemember() {
$expected = 'This is some data 0';
$result = Cache::remember('test_key', [$this, 'cacher'], 'default');
$this->assertEquals($expected, $result);

$this->_count = 1;
$result = Cache::remember('test_key', [$this, 'cacher'], 'default');
$this->assertEquals($expected, $result);
}

/**
* Method for testing Cache::remember()
*
* @return string
*/
public function cacher() {
return 'This is some data ' . $this->_count;
}
}

0 comments on commit f146d43

Please sign in to comment.