Skip to content

Commit

Permalink
Breaking out the find so that it can be easily overloaded for caching
Browse files Browse the repository at this point in the history
Before this commit you have to do some hacks to cache model finds easily. When using
custom find methods like `find('foo')` => `_findFoo(...)` it is common for the
method to adjust the query params.

Trying to cache a query using a hash of the query params :

	function find($type, $query) {
		$query = $this->_beforeFind($query);
		$cacheKey = $type . '_' . md5(selialize($query));

		$cache = Cache::read($cachKey, 'my_cache');
		if ($cacheKey !== false) {
			return $cache;
		}

		$results = $this->_afterFind($type, $query);
		Cache::write($cacheKey, $results, 'my_cache');

		return $results;
	}

Before this commit you either have to completely overload find and rewrite it in the AppModel or call
the before to get the modified `$query` and let cake run the before again.
  • Loading branch information
dogmatic69 committed Feb 9, 2013
1 parent 13029cc commit 00abe27
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions lib/Cake/Model/Model.php
Expand Up @@ -2678,14 +2678,39 @@ public function hasAny($conditions = null) {
* @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
*/
public function find($type = 'first', $query = array()) {
$this->findQueryType = $type;
$this->id = $this->getID();

$query = $this->buildQuery($type, $query);
$query = $this->_beforeFind($type, $query);
if (is_null($query)) {
return null;
}

return $this->_afterFind($type, $query);
}

/**
* Before running a find
*
* @param string $type the find type to run
* @param array $query the finds query params
*
* @return array|null
*/
protected function _beforeFind($type, $query) {
$this->findQueryType = $type;
$this->id = $this->getID();

return $this->buildQuery($type, $query);
}

/**
* After running a find
*
* @param string $type the find type to run
* @param array $query the finds query params
* @param array $results they results from the find
*
* @return array|null
*/
protected function _afterFind($type, $query) {
$results = $this->getDataSource()->read($this, $query);
$this->resetAssociations();

Expand All @@ -2702,6 +2727,7 @@ public function find($type = 'first', $query = array()) {
if ($this->findMethods[$type] === true) {
return $this->{'_find' . ucfirst($type)}('after', $query, $results);
}

}

/**
Expand Down

0 comments on commit 00abe27

Please sign in to comment.