【发布时间】:2017-08-08 00:40:40
【问题描述】:
我正在开发一个应用程序,并且正在为 REST API 使用 Repository-Service-Controller 方法。
我发现自己在控制器逻辑与服务逻辑之间争论不休。服务逻辑处理业务逻辑,例如计算图书价格,而控制器逻辑处理表示细节。
- 如果部分业务逻辑的
应用程序是检查发布者是否订阅了
PremiumService确定这本书是否可编辑?将 这是业务逻辑还是控制器逻辑? - 如果在控制器中,如果出版商未在
PremiumService中订阅,我想隐藏正在呈现的书籍怎么办?PremiumService是否会成为PublisherController的依赖项,以检查图书的出版商是否在PremiumService中订阅?
我可以看到在 BookService 上创建过多的依赖项会变成意大利面条式代码。
这是一个带有伪代码的界面,可以帮助回答我的问题。
class Publisher
{
public function getId(): int;
public function getName(): string;
public function getBooks(): Book[];
}
class Book
{
public function getId(): int;
public function getName(): string;
public function getPublisher(): Publisher;
public function getAuthors(): Author[];
}
class Author
{
public function getId(): int;
public function getName(): string;
public function getBooks(): Book[];
}
// Simple CRUD repository.
class BookRepository
{
public function find($id);
public function findAll($criteria);
public function create($book);
public function edit($book);
public function remove($book);
}
class BookService
{
public function __construct(
BookRepository $book_repository,
AuthorService $author_service,
PremiumService $subscription_service
);
public function get($id);
public function getAll($criteria);
// Book is editable if the publisher of the book is subscribed to the PremiumService
public function edit(Book $book);
// Book is removable if the publisher of the book is subscribed to the PremiumService
public function remove(Book $book);
// Can only add an author if the publisher of the book is subscribed to the PremiumService.
public function addAuthor(Author $author, Book $book);
}
class PublisherController
{
public function __construct(BookService $book_service);
// Can only view a book if the publisher of the book is subscribed to the PremiumService
public function getBook(Request $request);
// Can only view books if the publisher of the book is subscribed to the PremiumService
public function getBooks(Request $request);
}
如果一个服务依赖于其他服务的太多依赖项,这里通常或推荐的方法是什么?服务应该像存储库一样愚蠢吗?
【问题讨论】:
标签: design-patterns model-view-controller dependency-injection controller