列表接口的通用写法

列表类型的接口,因为客户端需要做分页,所以除了列表内容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();

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容