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)); default: 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'); $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.
For more practical examples, see my article here: http://c7y.phparch.com/c/entry/1/art,mvc_and_cake
Oops, didn’t notice you already had the link. :-P
Wouldnt $Model->find(‘recent’); work out of the box
It should call Model::_findRecent() according to Model.php line 1691-1695 ?
@nate: No problem :)
@Christian: Well, you can make it work in that way by adding “recent” => true to the $__findMethods array of the model. But as that array is meant to be private you shouldn’t manipulate it ;-)
‘list’ is another find() type
I think that the purpose of the “new kind” of find isnt fully explained in this post. When I first read this article, I also felt that the getRecent was more useful. But when I got the original article of Nate, dude, that´s evil genious :)
@jesse: Thanks, I forgot this one plus the “neighbors” type :| I fixed it in the article.
@Martin: Yes, that’s true. This article is about the “how” and not the “why” ;-)
Hey Daniel,
I’ve been reading your blog for quite some time now and it really helped me to master learning cakephp and it still does.
Anyway, in this post you wrote that there’s a new ‘neighbors’ method for the new find() syntax. And although the ‘neighbors’ key is in the __findMethods array it seems that this method is NYI. Can you confirm this? Or am I doing something wrong. I’m with SVN HEAD.
Thanks
@Michael: Yes, you are right, the method is not yet implemented. I added a hint in the article, thanks!
[…] 28, 2008 I know you’ve already red on phparch, cakebaker and debuggable about how to define diferent find types, but *happily* they are all […]
[…] I’m not sure whether this approach should be really used, as the approach with overriding the find() method seems to be easier (see my earlier article Defining custom find types). […]