Php – Service layer design

design-patternsmvcPHPservices

I am developing an MVC website in PHP, and for the first time, I would like to implement a service layer. I have some design considerations I would like to get some advice on. The backend will by no means be a large enterprise system, so I am looking to keep things relatively simple while still leveraging the benefits of a service layer.

The idea is that my controllers will interact with services, which in turn will interact with DAOs. My main question is how granular my services should be. I am familiar with the concept of service granularity in SOA, but have never implemented this in practice. For instance, to handle user registration, should I have a RegistrationService class, or should I have a UserService which contains a register method along with other user-related services? The former approach means that I will have a service layer full of small or fine-grained services, but I guess that is a good thing. The latter seems to hinder service reuse and result in large classes with many methods.

Instead, perhaps I should combine the two approaches to ensure that my services can be reused? For instance, have a RegistrationService which interacts with a DAO class. Then, I could have a UserService class with a register method. This method interacts with the fine-grained RegistrationService. This way, the RegistrationService can easily be reused to compose more coarse-grained services. Surely there are examples where the reuse would be more likely; for instance, placing an order would need to use/orchestrate many different services. I guess you could call this a "layered" approach, which I have seen discussed before. Could I structure this in a way such that my service layer will not become a mess?

I would love to hear your thoughts on this, whether you have other suggestions, recommendations and experiences or comments on the ideas I presented above. Thank you in advance.

Best Answer

Well, I think RegistrationService is more intent revealing.

One can easily speculate on what function can be found there such as registerUser(), ConfirmRegisteration(), ResetPassword(),...etc. To me most of them seem to fall logically in a RegisterionService class than a general UserService class.

A service layer is supposed to contain functions that operate on more than one Entity, so a UserService may not logically be the best place for such operations.