在Repository-Service-Controller模式中导出的类型

huangapple go评论73阅读模式
英文:

Exported types in Repository-Service-Controller Pattern

问题

如果你已经了解了Repository-Service-Controller模式,可以跳过下面的部分。


Repository-Service-Controller模式的简要解释。

在一个Go Web应用程序中,代码的组织结构如下:

main.go

server
|__clientdata.go

clientdata
|__controller.go
|__service.go
|__repository.go

main.go是入口点。它创建了一个服务器mux对象,并调用服务器包中定义的接收方法。这些方法定义了路由/端点,并将它们映射到它们各自包中的controller.go公开的handlefuncs

然后,控制器调用服务,服务再调用存储库-它们都在同一个包中。


但是,为什么服务和存储库方法是导出类型(即首字母大写),当在这个模式中它们是由同一个包中的控制器调用呢?

导出不必要的方法不是一种好的实践,对吗?

问题是:

那么,为什么它们被导出?如果我不导出它们,可以吗?

英文:

Skip below section, if you already know the Repository-Service-Controller pattern.


Brief explanation of Repository-Service-Controller pattern for context.

In a go web application, the following is the code organization-

main.go

server
|__clientdata.go

clientdata
|__controller.go
|__service.go
|__repository.go

main.go is the entry point. It creates a server mux object and calls the receiving methods defined on it in the server package. These methods define routes/endpoints and map them to their respective handlefuncs exposed by controller.go in their respective packages (here, package clientdata).

Then, the controller calls the service which in turn calls the repository- all of which are in the same package.


But, why are the service and repository methods exported types (ie, capitalized first letter) when in this pattern, they are called by the controller which is in the same package?

Isn't it a bad practice to export unnecessarily?

The question :-

So, why are they exported? Is it alright if I don't export them?

答案1

得分: -1

这是因为可以使用来自不同包的服务来组合一个新的控制器,同样地,可以使用来自不同包的存储库来组合一个新的服务(在需要时,参见下面的示例)。

例如,组合一个数据库服务,该服务同时使用内存缓存和持久化数据存储服务,如Redis和Mongodb,它们各自拥有自己的存储库。

希望这对新手(像我一样)有所帮助。

英文:

It is because services from from different packages can be used to compose a new controller and similarly, repositories from different packages can be used to compose a new service (when required, see example below).

For example, composing a database service that uses both in-memory caching and persistent data store services like Redis and Mongodb respectively with their own repositories.

Hope this helps newbies (like me).

huangapple
  • 本文由 发表于 2023年2月2日 01:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75314029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定