Sugar icing on the cake

Published on 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

    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

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

  • KesheR

    I ALWAYS forget to use this kind of functions.

  • Max

    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

    @all: Thanks for your comments.

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

  • Fred

    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

    @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