Sobes.tech
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() and afterValidate() — called before and after model validation.
  • beforeSave($insert) and afterSave($insert, $changedAttributes) — called before and after saving the model to the database. The $insert parameter indicates whether a new record is being created.
  • beforeDelete() and afterDelete() — 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.