Controller logic vs Service/Business layer logic

前端 未结 1 920
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 15:10

I am working on an application and am using a Repository-Service-Controller approach for a REST API.

I find myself debating between controller logic vs service logic

相关标签:
1条回答
  • 2021-01-02 15:49

    To answer your questions:

    1) You kind of answered your own question by saying "what if part of the business logic of the application is to..." Since it's business logic, put it in the business logic layer (i.e. service).

    2) Hiding books if publisher the isn't subscribed to a subscription service sounds like it's part of your business logic (your business rules are that users can't read books if they don't pay for them), so that would go in a service. And then yes, that service would have to be a dependency of your controller.

    I frequently find myself in a similar situation to yours, where a single business rule requires dependencies on a lot of business services in order to do its job. A good way of avoiding around having a ton of dependencies in your services, while keeping each service simple, is to use a facade service once you start getting to four or five dependencies for a service. The facade is a higher level service which handles coordinating the lower level services.

    For example, you could have a ContentManager service which takes dependencies of BookService, AuthorService, and PremiumService. Then your controller just has a single dependency on ContentManager. When your controller wants to display a list of books, it would call ContentManager.getBooks and pass in some user details so you can determine whether that user is subscribed or not. Then ContentManager determines whether the user can view a book, gets the book's details, gets the book's author details, and so on.

    Even though ContentManager ultimately has a lot of stuff going on underneath it in its sub-services, it's still a pretty simple class because its only job is to call the appropriate sub-service methods for a given action.

    Admittedly that's not a great improvement in your case because you don't have a ton of dependencies, but if you found yourself in a situation where a controller needed, say eight dependencies, then you could break those into facades. If five of those services were used for one set of high-level business rules (such as your library/publisher management) and three of those services were used for another set of high-level business rules (such as billing) then you'd have one facade with five dependencies and another facade with three dependencies.

    0 讨论(0)
提交回复
热议问题