Merge pull request #1704 from cakephp/2.5-cache

2.5 - Add Cache::remember()
This commit is contained in:
José Lorenzo Rodríguez 2013-10-06 07:02:54 -07:00
commit 9472b3149b
2 changed files with 60 additions and 0 deletions

View file

@ -542,4 +542,38 @@ class Cache {
throw new CacheException(__d('cake_dev', 'Invalid cache group %s', $group)); 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.
*
* Examples:
*
* Using a Closure to provide data, assume $this is a Model:
*
* {{{
* $model = $this;
* $results = Cache::remember('all_articles', function() use ($model) {
* return $model->find('all');
* });
* }}}
*
* @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. Can be any callable type supported by your PHP.
* @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;
}
} }

View file

@ -27,6 +27,8 @@ App::uses('Cache', 'Cache');
*/ */
class CacheTest extends CakeTestCase { class CacheTest extends CakeTestCase {
protected $_count = 0;
/** /**
* setUp method * setUp method
* *
@ -491,4 +493,28 @@ class CacheTest extends CakeTestCase {
$this->assertEquals('test_file_', $settings['prefix']); $this->assertEquals('test_file_', $settings['prefix']);
$this->assertEquals(strtotime('+1 year') - time(), $settings['duration']); $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', array($this, 'cacher'), 'default');
$this->assertEquals($expected, $result);
$this->_count = 1;
$result = Cache::remember('test_key', array($this, 'cacher'), 'default');
$this->assertEquals($expected, $result);
}
/**
* Method for testing Cache::remember()
*
* @return string
*/
public function cacher() {
return 'This is some data ' . $this->_count;
}
} }