afterSave if nothing has changed

Hi! Sorry for noob question but I think experienced users will answer it easily.

I’ve got the AR model with afterSave() defined and I’ve got the block of code to be executed only if the model has changed (some cache deleting). So, the question is: will afterSave() be triggered if there were no changes in the model?

For example:


$model = new Model;

// let's assume the model property 'name' is already equal 'Test'

$model->name = 'Test';

$model->save();

The afterSave() handler in the model:


public function afterSave($insert, $changedAttributes)

{

    if (parent::afterSave($insert, $changedAttributes)) {

        // some serious cache deleting here

        return true;

    }

    return false;

}

Should I check $changedAttributes for emptiness or the afterSave() will never be triggered if there were no changes?

If we look at the code, afterSave is triggered even if no data is modified (dirty attributes) :

But the function returns anything, so I think you will never enter in the condition :




if (parent::afterSave($insert, $changedAttributes)) { //HERE

  // some serious cache deleting here

  return true;

}



Try like this :




public function afterSave($insert, $changedAttributes)

{

  parent::afterSave($insert, $changedAttributes)

  // some serious cache deleting here

  ...

}



Timmy78, I actually need not to execute the afterSave() code if none has changed (no need to clean up a cache if everything stays the same).

But I need to be sure that it would not be executed if no dirty attributes.

In other words I can do that way:


if (parent::afterSave($insert, $changedAttributes) && !empty($changedAttributes)) { // here it is !empty() check

    // some serious cache deleting here

    return true;

}

The question is: do I need to do so or it is excess?

I think it’s a good way

Yii is extremly flexible, so you can what you want ^^

Timmy78, and it brings us to another question: will the attributes still be dirty? Remember, it’s afterSave(), and the manual says that attributes are dirty when they has been changed after the latest save().

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#dirty-attributes

Actually, I think this is the reason of existence of $changedAttributes in afterSave(). There is no other need in it if you can get them with getDirtyAttributes() any moment.