Search code examples
yii2modelsbehavior

Yii2 generic behaviour in all models


How Can I add a generic behaviour function that would work for all models. I have added this code in all models. Now I don't want to repeat the same function in all models.


Solution

  • You can create a CustomModel class that extends ActiveRecord. In CustomModel, add the method that you want:

    class CustomModel extends \yii\db\ActiveRecord {
         public function custom_function() {
             //Function details
         }
    }
    

    Then make your models extend CustomModel

    class Book extends CustomModel {
    
    }
    

    That way you can use this method in all your models that extends CustomModel without having to implement this method in each of them.