Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Breaking out the find so that it can be easily overloaded for caching

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...
commit 00abe27ef8c3d483fd2fcf34e2afdf8fd5230d76 1 parent 13029cc
@dogmatic69 dogmatic69 authored
Showing with 30 additions and 4 deletions.
  1. +30 −4 lib/Cake/Model/Model.php
View
34 lib/Cake/Model/Model.php
@@ -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();
@@ -2702,6 +2727,7 @@ public function find($type = 'first', $query = array()) {
if ($this->findMethods[$type] === true) {
return $this->{'_find' . ucfirst($type)}('after', $query, $results);
}
+
}
/**
Please sign in to comment.
Something went wrong with that request. Please try again.