CakePHP tip: Custom Find Types


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:


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:

var $_findMethods = array(
    'all' => true, 'first' => true, 'count' => true,
    'neighbors' => true, 'list' => true, 'threaded' => true

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:

class PostModel extends AppModel {
    var $_findMethods = array('latest' => true);

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.

function _findLatest($state, $query, $results = array()) {
    if ($state == 'before') {
        $query['limit'] = 10;
        $query['order'] = 'created DESC';
        return $query;
    } elseif ($state == 'after') {
        return $results;

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.

About the author

Zvonko Biškup

A passionate web developer with more than 13 years experience in PHP and other web related technology. My main interest is WordPress and new PHP frameworks.
Owner of Influendo Programming.
Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff.

<span class="dsq-postid" data-dsqidentifier="709">3 comments</span>

  • 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);


By Zvonko Biškup