on Tips

CakePHP tip: Custom Find Types

4 comments
cakephp1
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

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:

$Post->find('latest');

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.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Mohamed

    Cool tip. Thanks for sharing. Hope you will hav time to compete your cakephp series.

  • Pingback: Tweets that mention CakePHP tip: Custom Find Types | CodeForest -- Topsy.com

  • http://mynameisthom.blogspot.com thom

    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..

    • http://codeforest.net Zvonko Biškup

      Thanks, it is corrected now.