Using behaviors in a base model.

So I’m using a base model that simply has timestamp and blameable behaviors in it. When I put behaviors in my current model the base model behaviors are lost is this to be expected?

Yes, that’s how method inheritance works in PHP. Parent’s method won’t be called automatically, it must be called explicitly in child and the results must be merged.

In fact I wouldn’t recommend to inherit any behaviors from a base class. It might save a few lines of code but you lose most of the the benefits of composition over inheritance.

Remember to merge the array from parent class whenever you override the parent method, it is very common in Yii2, like rules(), scenarios(), …

The code I used is like:


public function behaviors(){

    return array_merge(parent::behaviors(), [

         'behavior1' => 'blahblahblah',

         // .....

    ]);

}

phtamas

Could you elaborate a little more on it?

Do you mean that you would not call the parent’s behaviors() to merge the behaviors, but would repeat the behavior definitions of the parent class in the child class if another behavior must be attached?

ah totally makes sense thanks folks.