How to apply a beforeSave to certain models only

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

  1. Posted August 5, 2006 at 4:01 pm | Permalink

    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?

  2. Posted August 5, 2006 at 5:42 pm | Permalink

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

  3. Posted August 5, 2006 at 9:29 pm | Permalink

    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?

  4. Posted August 8, 2006 at 10:52 am | Permalink

    @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.


%d bloggers like this: