Permalink
Browse files

Integrate cache writes to Query & add tests..

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 3, 2014
1 parent ff57e19 commit a87ee4927179d0c32587700e0377e9d63b06136c
Showing with 70 additions and 0 deletions.
  1. +3 −0 Cake/ORM/Query.php
  2. +14 −0 Cake/ORM/QueryCacher.php
  3. +53 −0 Cake/Test/TestCase/ORM/QueryTest.php
View
@@ -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;
View
@@ -19,6 +19,7 @@
use Cake\Cache\Cache;
use Cake\Cache\CacheEngine;
use Cake\ORM\Query;
use Cake\ORM\ResultSet;
use RuntimeException;
/**
@@ -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.
*
@@ -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.