abdulrehman176617's avatar

Habit of using Traits

I am watching a video

Video Title : How/When to Use Traits in Laravel

Comment 1 on video:

Traits are PHP way of overcoming the inability to do multi-inheritance in a class so when you use a trait in a class you need to think of it as inheriting a super-class which is the trait in this case

Comment 2 on video

Exactly this. Literally this.

Traits shouldn't be used to put code in another location to make your code look cleaner; it should be used to extend a class after you've already extended it via inheritance. They're not a replacement for jobs or service classes.

My opinion

I think traits are good for cleaning code as compare to services why to use services for clean code when i have habit to use it.

Why not trait does it effect performance?

Just want to konw what you guy think.

0 likes
1 reply
martinbean's avatar

@abdulrehman176617 I personally don’t see the problem with using traits to house related logic, and to wrap it up into a “component”. Rails does this and calls them “concerns”. You’ll find this terminology in the Laravel framework code. I’ve also adopted this convention myself.

As a concrete example, in my video on demand platform I have a Video model that has various pieces of functionality organised into traits. There’s traits with names such as Bookmarkable, Chapterable, Publishable, Rentable, and so on. These trait describe what functionality this model has. I extracted these into traits in case I wanted to support additional media types in the future, say for example, podcasts. There’s no reason why audio-only media like a podcast episode couldn’t contain chapters, be published/un-published, made available for rent, etc.

Please or to participate in this conversation.