doubiao7410 2019-06-19 17:29
浏览 63
已采纳

包内组织的Golang数据库层

I would like to hear some advice from Golang gurus. Imagine I have a package for database layer with many table which I should define structs and functions for them. As an example, I have a table called "MyObject" and define a struct for it.

type MyObject struct {
    RecID       int
    Name        string
}

Is it convenient for functions related to this table/struct I define receiver like this:

func (o MyObject) AllMyObjects() ([]MyObject, error) {
    // retreive all MyObjects by query
}


func (o *MyObject) OneMyObjects() (MyObject, error) {
    // retreive one MyObject by query
}

In this way as my db package get bigger by structs and functions, it will look cleaner and easier to call methods like this (although I should define 1 extra line):

var myobject MyObject
var myobjects,err = myobject.AllMyObjects()

rather than calling functions directly on package level (db is name of my package)

var myobjects,err = db.AllMyObjects()

Is this Go way of organizing code or do you have other advice for this?

  • 写回答

3条回答 默认 最新

  • duanqia9034 2019-06-19 21:30
    关注

    I like Ben Johnson's method explained here https://medium.com/@benbjohnson/standard-package-layout-7cdbc8391fc1

    The idea is to have your domain objects in your base package, then wrap the database/nosql/redis/whatever persistence layer as services in subpackages. When I do this, I end up with this sort of thing:

    • myobject.go (defines MyObbject struct, and MyObjectService interface, has things like maybe 'Get, Update')
    • mysql/
      • myobject_service.go (implements MyObjectService for mysql persistence)
    • redis/
      • myobject_service.go (implementation for redis)

    this allows you to pass around MyObjectService in your business logic and you don't even care how the persistence actually happens. A mysql.MyObjectService concrete struct tends to hold things like a pointer to the database connection. A cache package may store things in memory. Etc.

    So in other words, don't base your struct slavishly to the database, locking yourself into a particular implementation. Separate the business code logic from the act of persisting, and use interfaces to allow a consistent pattern to accessing persisted data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效