Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

scadh's avatar
Level 1

Traits and Services

I am fairly new to PHP and Laravel, coming from a long background in Java. I'm having a hard time wrapping my head around the distinction between Traits and Services and when each is best used. Due to my background, my inclination is always create a Service when I want to re-use code in multiple places. But, as I understand it, that's precisely what Traits in PHP are for -- ultimately being 'cut and pasted' into the containing class. I want to build my app in the smartest way possible but am struggling to find use cases that recommend a Trait or Service as being the better option. After some reading, the best I've got is "use a service to do something, use a trait to avoid duplication of code (often boilerplate code)".

An example from what I'm working on now: There are multiple locations in my app that will need to use the Google Maps API. I would want to put methods into some class (a Trait or Service) that would handle the building the request to the API and return the response to the caller. I think a Service is the better option in this case because the shared code performs a specific task and doesn't need to know anything about it's caller (e.g. "$this").

But I see Traits used all over the place for such purposes and am unclear why. Would appreciate any guidance you might have to help make this distinction more clear.

0 likes
2 replies
martinbean's avatar

@scadh Traits exist because PHP doesn’t support multiple inheritance, so developers can place code in a trait that they wish to use in multiple classes. It’s not a design pattern unto itself.

“Services” is one of those terms that doesn’t have a canonical definition, and means different things to different developers. But essentially, it’s a class that contains business logic of some sort, that can be used in multiple contexts, i.e. a HTTP controller, a console command, a queued job, etc.

1 like

Please or to participate in this conversation.