php和golang的思维转换问题

来源:4-6 改造频道页-正在热播功能

慕瓜9466948

2020-09-28

老师我之前是做php开发用的也是一套mvc框架,之前一直是在controller层用一个数组(比如下面的searchData
)

public function showMatchList()
    {
        $searchData['gameType'] = isset($_GET['game_type']) ? $_GET['game_type'] : -1;
        $searchData['matchName'] = isset($_GET['match_name']) ? $_GET['match_name'] : '';
        $searchData['matchType'] = isset($_GET['match_type']) ? $_GET['match_type'] : -1;
        // $searchData['openTime'] = empty($_GET['open_time']) ? date("Y-m-d", strtotime("-1 week")) : trim($_GET['open_time']);
        // $searchData['colseTime'] = empty($_GET['colse_time']) ? date("Y-m-d") : trim($_GET['colse_time']);
        $searchData['openTime'] = empty($_GET['open_time']) ? "" : trim($_GET['open_time']);
        $searchData['closeTime'] = empty($_GET['close_time']) ? "" : trim($_GET['close_time']);
        $gameType = $this->config_info;
        $res = (new matchModel)->getMatchList($searchData);
    }

然后把searchData传到model层

$where = [];
        $whereStr = '';
        $whereData = [];
        $query = [];
        if (!empty($data['gameType']) && $data['gameType'] >= 0) {
            $where[] = "game_type =:game_type";
            $whereData["game_type"] = $data['gameType'];
            $query[] = "game_type=" . $data['gameType'];
        }
        if (!empty($data['matchName'])) {
            $where[] = '`name` LIKE :name';
            $whereData['name'] = '%' . $data['matchName'] . '%';
            $query[] = "match_name=" . $data['matchName'];
        }
        if (!empty($data['openTime'])) {
            $where[] = 'open_time >=:open_time';
            $whereData['open_time'] = strtotime($data['openTime']);
            $query[] = "open_time=" . $data['openTime'];
        }
        if (!empty($data['closeTime'])) {
            $where[] = 'close_time <=:close_time';
            $whereData['close_time'] = strtotime(date('Y-m-d 23:59:59',strtotime($data['closeTime'])));
            $query[] = "close_time=" . $data['closeTime'];
        }

        if (is_numeric($data['matchType']) && (int)$data['matchType'] >= 0) {
            $where[] = 'status_check =:status';
            $whereData['status'] = $data['matchType'];
            $query[] = "status=" . $data['matchType'];
        }

        if (!empty($where)) {
            $whereStr .= " WHERE " . implode(' AND ', $where);
        }

再去拼接sql,我想问如果用go来实现这种写法应该怎么做?这是我现在的做法

Controller:

//频道页-热播列表
func (this *VideoController) ChannelHotList() {
   var searchData = make(map[string]interface{})
   channelId, _ := this.GetInt("channelId")
   if channelId == 0 {
      this.Data["json"] = ReturnError(4001, "先指定频道")
      this.ServeJSON()
   } else {
      searchData["channelId"] = channelId
      searchData["isHot"] = 1
      searchData["limit"] = 9
   }
   num, data, err := models.GetChannelRecommendList(searchData)
   if err == nil {
      this.Data["json"] = ReturnSuccess(0, "获取成功", data, num)
   } else {
      this.Data["json"] = ReturnError(4004, "没有相关内容")
   }
   this.ServeJSON()
}

Model:

func GetChannelRecommendList(searchData map[string]interface{}) (num int64, videosData []VideoData, err error) {
   var (
      where       []string
      whereString string
      whereData   []interface{}
      videos      []VideoData
      limit       string
   )
   o := orm.NewOrm()

   if _, ok := searchData["typeId"]; ok {
      where = append(where, "type_id=?")
      whereData = append(whereData, searchData["typeId"])
   }
   if _, ok := searchData["isHot"]; ok {
      where = append(where, "is_hot=?")
      whereData = append(whereData, searchData["isHot"])
   }
   if _, ok := searchData["channelId"]; ok {
      where = append(where, "channel_id=?")
      whereData = append(whereData, searchData["channelId"])
   }
   if _, ok := searchData["regionId"]; ok {
      where = append(where, "region_id=?")
      whereData = append(whereData, searchData["regionId"])
   }
   if _, ok := searchData["status"]; ok {
      where = append(where, "status=?")
      whereData = append(whereData, searchData["status"])
   } else {
      where = append(where, "status=1")
   }
   if _, ok := searchData["isRecommend"]; ok {
      where = append(where, "is_recommend=?")
      whereData = append(whereData, searchData["isRecommend"])
   }
   if where != nil {
      whereString = " WHERE " + strings.Join(where, " AND ")
   }
   if _, ok := searchData["limit"]; ok {
      limit = fmt.Sprintf(" LIMIT %d", searchData["limit"].(int))
   }
   sql := fmt.Sprintf("SELECT id,title,sub_title,add_time,img,img1,episodes_count,"+
      "is_end FROM video %s order by"+
      " episodes_update_time desc %s", whereString, limit)
   num, err = o.Raw(sql, whereData).QueryRows(&videos)
   //fmt.Println(videos)
   if err != nil {
      panic(err)
   }
   return num, videos, err
}

我看到网上有说其实map[string]interface{}的这种用法十分不好,应该用结构体struct但是如果用结构体的话,我在controller一个方法就要定义一个结构体会不会太凌乱了?谢谢老师

写回答

1回答

下雨le

2020-11-04

两种方式我都有用过,用map interface这种模式一般在写通用操作数据库时使用,比如我们的后台管理系统是通过积木式开发实现的,正常的增删改查功能只需要一个配置文件就可以实现,一般10分钟完成。因为这种涉及到sql的自动生成,并且不同的表结构里面的字段类型都是不一样的所以只有使用map interface这种模式了。像业务的开发我一般用教程的模式来开发,不过习惯在model中定义struct,最近也看了写别人的源码,跟个人习惯有关没有统一的方式,各种模式都有的。

0
0

从1到N实战Go改造PHP 慕优酷 视频网站

仿大厂千万级视频项目;Go+PHP一箭双雕

346 学习 · 142 问题

查看课程