You probably used some of the great built-in find types in CakePHP like find(‘all’) and find(‘count’). If you haven’t, here is an article on how to retrieve your data in CakePHP from CakePHP book.
This types are smart enough to retrieve data from database in any way you see fit.
But, there is a way to write your own custom find types. Then, you can use something like:
[code lang=”php”]
$Post->find(‘latest’);
[/code]
Yes, you will now tell me that you can use $Post->query to write custom SQL, but it is not efficient as this solution.
Cake’s base Model class has an attribute defined that keeps track of all the default find types. It
looks like this:
[code lang=”php”]
var $_findMethods = array(
‘all’ => true, ‘first’ => true, ‘count’ => true,
‘neighbors’ => true, ‘list’ => true, ‘threaded’ => true
);
[/code]
To create your custom find type you need to add it to this list. If your custom find type was latest you would do something like this:
[code lang=”php”]
class PostModel extends AppModel {
var $_findMethods = array(‘latest’ => true);
}
[/code]
So, in your Model class you would add new custom find method. Now you have to create the method that will be called. The method name must match the pattern _findCustomType. In our example it would be _findLatest.
[code lang=”php”]
function _findLatest($state, $query, $results = array()) {
if ($state == ‘before’) {
$query[‘limit’] = 10;
$query[‘order’] = ‘created DESC’;
return $query;
} elseif ($state == ‘after’) {
return $results;
}
}
[/code]
The trick behind this code is that this method will be called twice. Once before the database query is made and once after.
In the before state you will have access to the $query array, where you can set conditions, limit, order…all the usual find options. In the after state the $results array is passed. You can then alter $results to fit whatever you’re trying to do or just return it directly.
This way your CakePHP code is much more smaller and efficient.
Cool tip. Thanks for sharing. Hope you will hav time to compete your cakephp series.
It’s kinda old post, but I found it useful enough. Thank you. A lil bit correction at your third block-code :
class PostModel extends AppModel {
var _findMethods = array(‘latest’ => true);
}
should be :
class PostModel extends AppModel {
var $_findMethods = array(‘latest’ => true);
}
Thanks..
Thanks, it is corrected now.
Comments are closed.