New feature: model “filters”

Published on and tagged with cakephp  feature  tip

If you have a look at the source code of the model, you will notice several new methods: beforeFind(), afterFind(), beforeSave(), afterSave(), beforeDelete() and afterDelete(). They are like filters. A very simple example of how to use them:

// in your model
function beforeDelete()
{
    debug('beforeDelete');
    return true;
}

function afterDelete()
{
    debug('afterDelete');
}

These two methods are automatically called when you do a

$this->Model->del($id);

.

Well, at the moment I do not see any real use cases for these filters. But I am sure we will see some useful uses soon. What do you think?

5 comments baked

  • Joe

    There will be tons of uses for these! A quick example:

    Before you delete a user record, you check to see if that user “owns” other records. If they do, clean up those records, too. Of course this could be done more cleanly with cascading deletes, but it was just an example.

    Another use would be for 3rd party plugins that can hook into the application but not really into the db structure. And finally, debugging..

  • Sam D

    other ways it could be used would be for the creation and use of virtual fields, like a firstLastName that is a concat of firstName and lastName.

  • Felix Geisendörfer

    I think this stuff is called “event oriented programming” and it gives you some neat ways of doing things. But on the other hand these functions won’t be too useful unless they get in a parameter about what was deleted and maybe some more information too …

  • Nate

    Actually, I only added those because I had several use cases for them in various projects I was working on at the time. As far as extra parameters, all the information you need is in the Model object itself.

  • cake baker » beforeSave() example

    […] I wrote already about the new model callback functions like beforeSave() and afterSave(). At that time I wondered what the use cases of these callbacks would be. Now I saw an opportunity for using the beforeSave() callback for storing datetime information. […]

Bake a comment




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

© daniel hofstetter. Licensed under a Creative Commons License