ActiveRecordTrait

Why we can not implement ActiveRecord as trait?
Requirement to extend ActiveRecord class is one of the main disadvantage of the ActiveRecord pattern comparing with DataMapper. And it seems this can be avoided by implementing the ActiveRecord class as trait.

And by meaning looks like ActiveRecord is trait. Because it is not about entity type/class, but about entity behavior. When I write class Car extends ActiveRecord, it sounds strange. Because it is wrong structure.

If you used Trait instead to extend ActiveRecord, where would you save $attributes, for example?

Same thing for relations, etc…etc…

From docs:

Traits can also define properties.

Without talking about OOP implications of Trait, what would be the practical differences between using traits with methods and properties and extends a base class?

1 Like

Same practical difference as with using DataMapper. Do you see main difference between ActiveRecord and DataMapper?
You can extend your entity from whatever class you want (but with ActiveRecord pattern you must extend ActiveRecord class). There are a lot of use cases:

  • imagine you use two libs/frameworks and everyone requires you extends your entity from their class (so it became the rule of good tone for lib’s/framework’s developer - make trait if it possible, not class, so user can use multiple inheritance)
  • (special case of the above case) imagine you already have your business logic with entities which have own parents

Apparently you just have not encountered such a problem, but it is serious. That is why DataMapper pattern exists.

Also implementing ActiveRecordTrait give us ability simply implement ActiveRecord for users who want it and for backward compatibility. Just do (but this is superfluous):

class ActiveRecord {
    use ActiveRecordTrait;
}

I’m sure, Yii core team see difference between ActiveRecord and DataMapper. I just want draw their attention to this idea (maybe their minds are clouded and they are at the mercy of the stereotype “we should do so, because Qiang Xue write so”). And if it is realizable, then it should be done. This makes an excellent Yii ActiveRecord implementation even better.
I was a fan of Yii ActiveRecord (and did not understand why I need something else), but when I ran into the problem described above, I began to see clearly.

These are not real examples. Why would you want something that is not active record to behave as active record?

2 Likes