Comparing Yii Behaviours and Native PHP Traits

Comparing Yii Behaviours and Native PHP Traits

Last updated:

PHP Traits and Yii Behaviours are implementations of the mixin object composition pattern, which allows you to share behaviour among classes; it is, therefore, an alternative to inheritance trees.

According to GOF's Design Patterns, we should favour composition over inheritance whenever possible.

Favor 'object composition' over 'class inheritance'. - (Gang of Four 1995:20)

TODO these are two ways to implement this when using Yii...

TODO an example of each


You can add Yii Behaviours at runtime (this is beautiful and allows massive uncoupling) but you can only add Traits to a class at code writing time.

IDE behaviour

IDEs will probably pick-up code from Traits if they see the use keyword at the beginning of you class code; this means that things like inteli-sense and code-completion, as well as code suggestions will probably not work for Yii Behaviours.


You can parameterize Yii Behaviours and you can't do so with native PHP Traits. This allows for a little bit of extra flexibility in Yii Behaviours as compared to Traits.

Dialogue & Discussion