列表接口的通用写法

2019-10-28  本文已影响0人  凡心往事

列表类型的接口,因为客户端需要做分页,所以除了列表内容list之外,必须返回总数total。

同时,列表接口常常需要兼顾搜索的功能。

列表接口处理过程,可以分为:接收参数,参数校验,处理搜索参数,获取列表总数,获取列表内容(考虑缓存),返回json数据。

1、接口参数

offset 分页

limit  每页显示数量

keyword  搜索关键字,看业务实际需求,可以是一个或多个搜索参数

_checkParams()  参数校验

2、搜索处理 & 获取总数

getSearchParam() 方法用户处理需要搜索的参数

getCoupon()  方法用户获取列表的数量

3、简要代码如下

CouponController 中的代码:

public function  getCouponList() {

        $offset = $this->param['offset'];

        $limit = $this->param['limit'];

        // 参数校验略,调用  _checkParam();

        $searchParam = $this->getSearchParam();

        $total = D('Coupon')->getCount($searchParam);

        $couponList = D('Coupon')->getCouponList($searchParam, $offset, $limit);

        $result = [

                'errno' => 0,

                'message' => 'success',

                'result' => [

                        'total' => $total,

                        'coupon_list' => $couponList

                ]

        ];

        $this->ajaxReturn($result);

}

private function _checkParam() {}

protected function getSearchParam() {

        $searchParam = [];

        $couponName = $this->param['coupon_name'];

        $couponType = $this->param['coupon_type'];

        $couponName && $searchParam['coupon_name'] = ['LIKE' , '%' . $couponName . '%'];

        $couponType && $seachParam['coupon_type'] = $couponType;

        return $searchParam;

}

CouponModel 中的方法:

public function getCount($searchParam) {

        return $this->where($searchParam)->count();

}

public function getCouponList($searchParam, $offset = 0, $limit = 10) {

        return $this->where($searchParam)->limit($offset, $limit)->select();

}

上一篇 下一篇

猜你喜欢

热点阅读