Defining custom find types

Published on and tagged with cakephp  model

The new notation for find statements comes with three five predefined find types: “all”, “first”, “count”, “list”, and “neighbors” (not yet implemented). But you can also define your own find types by overriding the find method.

If you want, for example, a “recent” find type for returning the most recent posts first, you could define it as shown in the following snippet:

// app/models/post.php
class Post extends AppModel {
    public function find($type, $options = array()) {
        switch ($type) {
            case 'recent': 
                return parent::find('all', array_merge(array('order' => 'Post.created DESC'), $options));
                return parent::find($type, $options); 

This custom find type can then be used in the same way as the other find types:

$this->Post->find('recent', array('limit' => 25));

Personally, I prefer to define a specialized method like:

// app/models/post.php
class Post extends AppModel {
    public function getRecent() {
        return $this->find('all', array('order' => 'Post.created DESC'));

But I think it is simply a matter of taste which approach you use.

[via Best Practices in MVC Design with CakePHP]

11 comments baked

Bake a comment

(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License