Junior — Middle
Which methods are automatically called on certain events in Yii2?
sobes.tech AI
Answer from AI
In Yii2, there are several methods that are called automatically during certain lifecycle events of a model or component. The main ones are:
init()— called after object creation, used for initialization.beforeValidate()andafterValidate()— called before and after model validation.beforeSave($insert)andafterSave($insert, $changedAttributes)— called before and after saving the model to the database. The$insertparameter indicates whether a new record is being created.beforeDelete()andafterDelete()— called before and after deleting the model.afterFind()— called after loading the model from the database.
Additionally, Yii2 uses an event system where you can subscribe to events and execute code when they occur.
Example of overriding a method:
class Post extends \yii\db\ActiveRecord
{
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
// additional logic before saving
return true;
}
}
Thus, these methods allow you to inject logic at key stages of working with models.