beforeSave() method implementation

I have seen various different ways of implementing the beforeSave() method, for example:

/**
 * Method 1
 */
public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    // code here

    return true;
}

/**
 * Method 2
 */
public function beforeSave($insert)
{
    parent::beforeSave($insert);

    // code here

    return true;
}

/**
 * Method 3
 */
public function beforeSave($insert)
{
    // code here

    return parent::beforeSave($insert);
}

They all work, as far as I am aware, but what is the correct / recommended way of doing it?

It all depends on what your needs are…

Example 1 - will not run your code if a parent beforeSave() do not pass (return false)

Example 2 - will run your code even if parent beforeSave() do not pass… but fixing returning “true” is not good :wink:

Example 3 - will run your code before some parent beforeSave() code, for example if you want to adjust some data before sending it to other beforeSave() code

3 Likes

@mdomba is right: it depends.

When you review a method that looks like Example 1 you know that the parent’s beforeSave and the triggering of events is independent of what follows. That makes it a bit easier to think about so I prefer this when possible.