业务逻辑层

XYGo Admin 2025-02-20 85 次阅读

Logic 层与 Service 层的开发规范

业务逻辑层

架构说明

  • Service 层:定义接口(由 gf gen service 自动生成,勿手动修改)
  • Logic 层:实现接口(核心业务代码写在这里)

编写 Logic

1. 创建 Logic 文件

go 复制代码
// internal/logic/example/example.go
package example

import (
    "context"
    api "xygo/api/admin"
    "xygo/internal/dao"
    "xygo/internal/service"
)

func init() {
    service.RegisterExample(New())
}

func New() *sExample {
    return &sExample{}
}

type sExample struct{}

2. 实现业务方法

go 复制代码
// 列表查询
func (s *sExample) List(ctx context.Context, req *api.ExampleListReq) (res *api.ExampleListRes, err error) {
    res = &api.ExampleListRes{}
    m := dao.Example.Ctx(ctx)

    if req.Title != "" {
        m = m.WhereLike("title", "%"+req.Title+"%")
    }

    res.Total, err = m.Count()
    if err != nil {
        return
    }

    err = m.Page(req.Page, req.PageSize).
        OrderDesc("id").
        Scan(&res.List)
    return
}

// 编辑(新增+修改)
func (s *sExample) Edit(ctx context.Context, req *api.ExampleEditReq) (res *api.ExampleEditRes, err error) {
    data := do.Example{
        Title:  req.Title,
        Status: req.Status,
    }
    if req.Id > 0 {
        _, err = dao.Example.Ctx(ctx).Where("id", req.Id).Data(data).Update()
    } else {
        _, err = dao.Example.Ctx(ctx).Data(data).Insert()
    }
    return
}

// 删除
func (s *sExample) Delete(ctx context.Context, req *api.ExampleDeleteReq) (res *api.ExampleDeleteRes, err error) {
    _, err = dao.Example.Ctx(ctx).Where("id", req.Id).Delete()
    return
}

3. 注册到 logic.go

internal/logic/logic.go 中添加导入:

go 复制代码
package logic

import (
    _ "xygo/internal/logic/example"
    // ... 其他模块
)

4. 生成 Service 接口

bash 复制代码
gf gen service

这会自动在 internal/service/ 下生成 example.go,包含接口定义和注册函数。

注意事项

  • Logic 中的 init() 函数负责将实现注册到 Service
  • 所有数据库操作通过 DAO 层进行,不要直接写 SQL
  • 事务操作使用 dao.Example.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error { ... })