Sugar icing on the cake

Published on January 23, 2007 and tagged with cakephp  magic  model

Probably every framework and programming language provides some functionality which is nice to have but not that essential. An example are the magic find functions in CakePHP. With this magic you can write the following statement to return all users named “Miller”:

$this->User->findAllByName('Miller');

The same statement without magic looks like:

$this->User->findAll(array('User.name' => 'Miller'));

CakePHP 1.2 introduces some more magic, it is now possible to define a “find” over multiple fields. Say, you want to find all users named “Miller” born in 1970. You can accomplish that with:

$this->User->findAllByNameAndYearOfBirth('Miller', 1970);

And without magic:

$this->User->findAll(array('User.name' => 'Miller', 'User.year_of_birth' => 1970));

As you see you have to type lesser thanks to the magic. You can also use OR in the magic find functions (but you cannot mix AND and OR). So to find all users named “Miller” and/or born in 1970 you can do:

$this->User->findAllByNameOrYearOfBirth('Miller', 1970);

And without magic:

$this->User->findAll(array('or' => array('User.name' => 'Miller', 'User.year_of_birth' => 1970)));

I am not sure if this will work with PHP4, as far as I remember you have to use a slightly different syntax.

7 comments baked

  • kabturek January 23, 2007 at 13:28

    gr8
    this one i didn’t know ( the ‘or’ part):
    $this->User->findAll(array(‘or’ => array(‘User.name’ => ‘Miller’, ‘User.year_of_birth’ => 1970)));
    is it 1.2 only ?
    got to write it somewhere :)

  • nate January 23, 2007 at 16:37

    PHP4 can only pick up method names in lowercase, so you’d have to do findAllByName_or_year_of_birth(…).

  • KesheR January 23, 2007 at 17:15

    I ALWAYS forget to use this kind of functions.

  • Max January 24, 2007 at 00:48

    Great… I’m happy to see such a great progress with Cake daily…. I am trying to apply this to a search function… I’m sure this is going to reduce 10-12 lines of code.. Loved it !!!!

    There’s also a small hack which I’m gonna try..

  • cakebaker January 24, 2007 at 11:48

    @all: Thanks for your comments.

    @kabturek: The “or” is afaik available since 1.1.something.

  • Fred January 28, 2007 at 10:11

    Having fought with some bug (https://trac.cakephp.org/ticket/2008) in Cake this week, I happen to know that this code is not only in the cake 1.2 code but in 1.1.12 as well.

    I am pretty sure it works with php4 as well too, only there the capitalization won’t work. Instead you’ll have to resort to underscores.

  • cakebaker January 28, 2007 at 12:39

    @Fred: Yes, you are right, it is also available in 1.1.12. Thanks for the correction.

    Yes, it works with PHP4, see Nate’s comment.

Bake a comment




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

© daniel hofstetter. Licensed under a Creative Commons License