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

包内组织的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条)

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch