Named Scopes in CakePHP

Ruby on Rails 2.1 introduced the concept of named scopes. During a friday afternoon we discussed named scopes and wanted to have it available for us to use. We ended up modifying an existing behavior for CakePHP to make it a little bit easier to use.

Named scopes are essentially a shorthand for a frequently used set of conditions you need when you want to query your model. So if you have a User model and you want to find all the active users which are named “Joe”, you would normally end up with this:

$this->User->find(array('conditions' => array('is_active' => 1, 'name' => 'Joe')));

Using named scopes you can write it like this:

$this->User->active->find(array('conditions' => array('name' => 'Joe')));

Which is not only shorter to write, but also easier to read. And it also leads to better maintainable code.

Our modified behavior requires you to modify your app_model (Without it, the $this->User->active shorthand will not work). You can read the installation and usage instructions on github, where you can also find the code. Enjoy!

Tagged

2 Responses to Named Scopes in CakePHP

  1. Nice job but were you guys aware Joel Moss built this in 2008? https://github.com/joelmoss/cakephp-namedscope

  2. Heh, no not at all ;-) (I suppose this may be a bit sloppy on my part, but it was a friday afternoon project ;) )

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>