Skip to content

Commit

Permalink
Integrate cache writes to Query & add tests..
Browse files Browse the repository at this point in the history
Once we have a result set we can cache it and return it. Ensure that
cache reads and writes happen. Don't write to the cache when we read
data from the cache. This might result in infinitely cached data.
  • Loading branch information
markstory committed Jan 4, 2014
1 parent ff57e19 commit a87ee49
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cake/ORM/Query.php
Expand Up @@ -517,6 +517,9 @@ public function getResults() {
$results = $this->_decorateResults(
new ResultSet($this, $this->execute())
);
if ($this->_cache) {
$this->_cache->store($this, $results);
}
}
$this->_results = $results;
return $this->_results;
Expand Down
14 changes: 14 additions & 0 deletions Cake/ORM/QueryCacher.php
Expand Up @@ -19,6 +19,7 @@
use Cake\Cache\Cache;
use Cake\Cache\CacheEngine;
use Cake\ORM\Query;
use Cake\ORM\ResultSet;
use RuntimeException;

/**
Expand Down Expand Up @@ -64,6 +65,19 @@ public function fetch(Query $query) {
return $result;
}

/**
* Store the result set into the cache.
*
* @param Query $query The query the cache read is for.
* @param ResultSet The result set to store.
* @return void
*/
public function store(Query $query, ResultSet $results) {
$key = $this->_resolveKey($query);
$storage = $this->_resolveCacher();
return $storage->write($key, $results);
}

/**
* Get/generate the cache key.
*
Expand Down
53 changes: 53 additions & 0 deletions Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -1547,4 +1547,57 @@ public function testCacheErrorOnNonSelect() {
$query->cache('my_key');
}

/**
* Integration test for query caching.
*
* @return void
*/
public function testCacheReadIntegration() {
$query = $this->getMock(
'\Cake\ORM\Query', ['execute'],
[$this->connection, $this->table]
);
$resultSet = $this->getMock('\Cake\ORM\ResultSet', [], [$query, null]);

$query->expects($this->never())
->method('execute');

$cacher = $this->getMock('Cake\Cache\CacheEngine');
$cacher->expects($this->once())
->method('read')
->with('my_key')
->will($this->returnValue($resultSet));

$query->cache('my_key', $cacher)
->where(['id' => 1]);

$results = $query->all();
$this->assertSame($resultSet, $results);
}

/**
* Integration test for query caching.
*
* @return void
*/
public function testCacheWriteIntegration() {
$table = TableRegistry::get('Articles');
$query = new Query($this->connection, $table);

$query->select(['id', 'title']);

$cacher = $this->getMock('Cake\Cache\CacheEngine');
$cacher->expects($this->once())
->method('write')
->with(
'my_key',
$this->isInstanceOf('Cake\ORM\ResultSet')
);

$query->cache('my_key', $cacher)
->where(['id' => 1]);

$query->all();
}

}

0 comments on commit a87ee49

Please sign in to comment.