Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly call parent:: in beforeSave, beforeValidate, afterSave etc

Tags:

php

yii

In the Yii documentation we can often read "Make sure you call the parent implementation so that the event is raised properly." for beforeSave, beforeValidate, afterSave ...

In the Yii Blog Tutorial I've seen:

protected function beforeSave()
{
    if(parent::beforeSave())
    {
        ...
        return true;
    }
    else
        return false;
}

What's up with the if-function?

I've also seen just simply:

protected function afterSave()
{
    parent::afterSave();
    ...
}

And:

protected function beforeValidate()
{
    ...
    return parent::beforeValidate();
}

Why do you sometimes wrap the parent::function call in a if-function?
Does it matter if I just call the parent::function(); in the beginning or return it in the end?

like image 360
DaveSthlm Avatar asked Dec 26 '22 11:12

DaveSthlm


1 Answers

It depends on what you would like to do.

You should know that beforeSave and beforeValidate methods can affect the further process of saving/validation by returning true or false, whether afterSave and afterValidate - can't. You should also know that you can have not just one event handler, but any number of them, attached using attachEventHandler method. So, considering this, the place where you call parent function does matter in case of beforeSave and beforeValidate methods when you have multiple event handlers. In other cases it doesn't.

For example, you have beforeSave() handler in your model, and you have also subscribed to this event in another class (it all based on Observer pattern, i suggest you to read about it to understand the events more deeply). When you're implementing beforeSave() method, you must call parent::beforeSave() to make that other event handler work. And if you've decided that you should not save your model for some reason, you have a choice - whether to run other event handlers or not. So you can return false immediately wihout letting other event handlers being fired (and save some resources may be).

If you consider your own beforeSave() handler less important than other attached handlers, then you should call parent::beforeSave() first, check it's result (like you did in your first example) and execute your code depending on what other event handlers decided to do.

Usually you won't have additional event handlers in your models (if you have, you probably should understand your question yourself), so you can always call parent method in return statement, like in your last examples. And if you want to interrupt the saving or validation, return false instead.

like image 197
Anton Sergeyev Avatar answered Jan 19 '23 01:01

Anton Sergeyev