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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?