列表類型的接口,因為客戶端需要做分頁料按,所以除了列表內(nèi)容list之外奄侠,必須返回總數(shù)total。
同時站绪,列表接口常常需要兼顧搜索的功能遭铺。
列表接口處理過程,可以分為:接收參數(shù)恢准,參數(shù)校驗魂挂,處理搜索參數(shù),獲取列表總數(shù)馁筐,獲取列表內(nèi)容(考慮緩存)涂召,返回json數(shù)據(jù)。
1敏沉、接口參數(shù)
offset 分頁
limit? 每頁顯示數(shù)量
keyword? 搜索關(guān)鍵字果正,看業(yè)務(wù)實際需求,可以是一個或多個搜索參數(shù)
_checkParams()? 參數(shù)校驗
2盟迟、搜索處理 & 獲取總數(shù)
getSearchParam() 方法用戶處理需要搜索的參數(shù)
getCoupon()? 方法用戶獲取列表的數(shù)量
3秋泳、簡要代碼如下
CouponController 中的代碼:
public function? getCouponList() {
?? ??? ?$offset = $this->param['offset'];
?? ??? ?$limit = $this->param['limit'];
? ? ? ? // 參數(shù)校驗略,調(diào)用 ?_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();
}