From 00abe27ef8c3d483fd2fcf34e2afdf8fd5230d76 Mon Sep 17 00:00:00 2001 From: dogmatic69 Date: Sat, 9 Feb 2013 16:09:50 +0000 Subject: [PATCH] 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. --- lib/Cake/Model/Model.php | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/lib/Cake/Model/Model.php b/lib/Cake/Model/Model.php index afb547baf..3c15d38cf 100644 --- a/lib/Cake/Model/Model.php +++ b/lib/Cake/Model/Model.php @@ -2678,14 +2678,39 @@ class Model extends Object implements CakeEventListener { * @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 @@ class Model extends Object implements CakeEventListener { if ($this->findMethods[$type] === true) { return $this->{'_find' . ucfirst($type)}('after', $query, $results); } + } /**