Traits vs (Data)Extensions in SS4 PHP7

I am wondering about the relationship between the PHP7 native “Trait” and SS native (Data) Extensions. Should I refactor (Data)Extensions to become Traits when working with SS4? Any comments and ideas welcome.

NOTE Extensions work differently in SS4: 4.0.0 – SilverStripe Documentation

1 Like

Traits are great if you own everything in the code, but you cannot add a trait to a class without modifying it. So it’s bad if you just want to add some custom functionality to a module you install via composer.

The biggest advantage of SilverStipe’s Extensions is, that you can add it through the config layer. You don’t have to touch 3rd party code while plugging an Extension to it.

The biggest disadvantage IMHO is the confusion between (Data)Extension and MyClass extends SomeClass aka subclassing.

Interesting points. Thank you for responding. From what you are saying, what would be really cool is a system where you can add traits to a “READ ONLY” class. That appears not to be very easy at all … php - How can I conditionally make a class use a trait if it exists? - Stack Overflow. It is a shame that PHP does not allow traits to be added at run-time.

I think they are two different things.

Imagine traits as copy-paste of code, which you write once and “paste” it to different classes through the use of use.

Extensions, as mentioned, can be applied via the config system to basically anything that supports it and I’d say they have a bit better integration with the ecosystem, they are SS extensions.

So I wouldn’t refactor one to the other as they are different concepts.

1 Like

Thank you for all your replies. That makes a lot of sense and I can see the difference much better now. However, it still seems to me that there may be a small subset of extensions that would be easier as traits because they just run more seamless (e.g. no $this->owner stuff).