How to apply a beforeSave to certain models only

Published on and tagged with cakephp  tip

This post is the answer to a question asked by Ian Hill in a comment to my previous post:

Is there a similar way to stop custom functions (especially beforeSave()) from being called in your model?

I hope I understood the question correctly and the following example answers the question ;-)

// app/app_model.php
class AppModel extends Model
    function beforeSave()
        if ($this->name != 'MyModel')
            // execute beforeSave logic
        return true;

4 comments baked

  • Patrice

    Never worked with CakePHP, but I guess MyModel inherits from AppModel? In that case wouldn’t it be cleaner to just override beforeSave() in MyModel and do nothing?

  • cakebaker

    Yes, you are right, that’s a cleaner solution. Thanks.

  • Brandon P

    I run into this question many times but mostly doesn’t.

    Example: I have a counterCache implemntation that automatically updates a count field on an associated table (belongsTo relationship)

    ForumPost belongsTo Forum (counterCache: forum_post_count)

    So everytime a ForumPost is created it will count up and store all ForumPosts’ by counting with the foriegnKey (in this case forum_id) as the condition. Quite useful and VERY helpful for stuff like Categories.product_count, Forum.forum_post_count, etc ..

    It would be nice to take this 1 step futher and suggest the use of flags for turning off these callbacks:

    $this->ForumPost->_afterSave = false;

    Also, I think findCount () should NOT call the afterFind () callback for obvious reasons. Agree/disagree?

  • cakebaker

    @Brandon P: Using flags is a good idea. Calling afterFind() after findCount() makes imho not much sense, at least I don’t see a use case for that at the moment.

© daniel hofstetter. Licensed under a Creative Commons License