thinkPHP分頁功能圖文詳解

來源:互聯網
上載者:User
這篇文章主要介紹了thinkPHP分頁功能,結合完整執行個體形式分析了thinkPHP基於商品模型實現分頁功能的相關操作技巧,需要的朋友可以參考下

本文執行個體講述了thinkPHP分頁功能。分享給大家供大家參考,具體如下:

interface ServiceInterFace:

<?php/** * InterFaceService * @author yhd */namespace Red;interface ServiceInterFace {  /**   * 執行個體化當前類   */  public static function getInstance();}

StaticService 靜態服務類:

<?php/** * 靜態服務類 * StaticService * @author yhd */namespace Red;class StaticService{  protected static $data;  /**   * 設定待用資料   * @param string $key key   * @param mixed $data data   * @return mixed   */  public static function setData($key,$data){    self::$data[$key] = $data;    return self::$data[$key];  }  /**   * 通過引用使用待用資料   * @param string $key key   * @return mixed   */  public static function & getData($key){    if(!isset(self::$data[$key])){      self::$data[$key] = null;    }    return self::$data[$key];  }  /**   * 緩衝執行個體化過的對象   * @param string $name 類名   * @return 對象   */  public static function getInstance($name){    $key = 'service_@_'.$name;    $model = &self::getData($key);    if($model === null){      $model = new $name();    }    return $model;  }  /**   * html轉義過濾   * @param mixed $input 輸入   * @return mixed   */  public static function htmlFilter($input){    if(is_array($input)) {      foreach($input as & $row) {        $row = self::htmlFilter($row);      }    } else {      if(!get_magic_quotes_gpc()) {        $input = addslashes($input);      }      $input = htmlspecialchars($input);    }    return $input;  }}

abstract AbProduct 抽象商品管理類:

<?php/*** 抽象商品管理類* AbProduct.class.php* @lastmodify 2015-8-17* @author yhd*/namespace Red\Product;abstract class AbProduct{  public $errorNum;  /*  *返回錯誤資訊  *@param $errorNum 錯誤碼  */  public function GetStatus(){    $errorNum = $this->errorNum;    switch($errorNum){        case 0:            $data['status'] = 0;            $data['message'] = '收藏成功';            break;        case 1:            $data['status'] = 1;            $data['message'] = '收藏失敗';            break;        case 2:            $data['status'] = 2;            $data['message'] = '已收藏';            break;        case 3:            $data['status'] = 3;            $data['message'] = '未登陸';            break;        case 4:            $data['status'] = 4;            $data['message'] = '缺少參數';            break;        default:            $data['status'] = 200;            $data['message'] = '未知錯誤';    }    return $data;  }

MemberModel 會員模型:

<?php/*** 會員模型* MemberModel.class.php* @copyright (C) 2014-2015 red* @license http://www.red.com/* @lastmodify 2015-8-17* @author yhd*/namespace Red\Passport\Models;use Think\Model;use Red\ServiceInterFace;use Red\StaticService;class MemberModel extends Model implements ServiceInterFace{  protected $userId;  protected $error;  protected function _initialize(){    $this->userId = getUserInfo(0);  }   /**   * 執行個體化本類   * @return MemberModel   */  public static function getInstance() {    return StaticService::getInstance(__CLASS__);  }   /**   *  擷取登入使用者資訊   * @param string  $data 查詢條件   * @return array   */  public function getUser($data = '') {    if(empty($data)){      return $this->where("id=".$this->userId)->find();    }else{      return $this->field($data)->where("id=".$this->userId)->find();    }  }  /**   * 修改使用者資訊   * @param array $data   * @param array $where 查詢條件   */  public function editUserInfo($data, $where = '') {    if( $this->_before_check($data) === false ){      return $this->error['msg'];    }    if(!empty($where) && is_array($where)){      $condition[ $where[0] ] = array('eq', $where[1]);      return $this->where($condition)->save($data);    }    return $this->where("id=".$this->userId)->save($data);  }  /**   * 擷取使用者資訊   * @param string $data 使用者名稱   * return array()   */  public function checkUserInfo($str, $field = ''){    //註冊類型    $info = CheckType($str);    $condition[$info] = array('eq',$str);    if(!empty($field)){      return $this->field($field)->where($condition)->find();    }    return $this->where($condition)->find();  }  /**   * 擷取使用者資訊   * @param array $data 使用者名稱   * return array()   */  public function getAccount($data){    //註冊類型    $info = CheckType($data);    $condition['id'] = array('eq',$this->userId);    $condition[$info] = array('eq',$data);    return $this->where($condition)->find();  }  /**   * 修改使用者密碼   * @param array $data['id']使用者ID   * @param $data['passWord']使用者密碼   * return true or false   */  public function upUserPassById($data){    $condition['id'] = array('eq',$data['id']);    $status = $this->where($condition)->save(array("password"=>md5($data['password'])));    if($status){        return TRUE;    }else {        return FALSE;    }  }  /**   * 校正使用者的帳號或者密碼是否正確   * @param $data['username'] 使用者名稱   * @param $data['password'] 密碼   * return true or false   */  public function checkUserPasswd($data= array()){      $type = CheckType($data['username']);      $condition[$type] = array('eq',$data['username']);      $condition['password'] = array('eq',md5($data['password']));       return $this->where($condition)->find();  }  /**   * 網頁登入校正token   * @param token string   * return bool   */  public function checkToken($token){      return $this->autoCheckToken($token);  }  /**   * 後台封號/解鎖   * param int $user_id   */  public function changeStatus($data){    if($this->save($data)){      return true;    }else{      return false;    }  }  protected function _before_check(&$data){    if(isset($data['username']) && empty($data['username'])){      $this->error['msg'] = '請輸入使用者名稱';      return false;    }    if(isset($data['nickname']) && empty($data['nickname'])){      $this->error['msg'] = '請輸入暱稱';      return false;    }    if(isset($data['realname']) && empty($data['realname'])){      $this->error['msg'] = '請輸入真名';      return false;    }    if(isset($data['email']) && empty($data['email'])){      $this->error['msg'] = '請輸入郵箱';      return false;    }    if(isset($data['mobile']) && empty($data['mobile'])){      $this->error['msg'] = '請輸入手機號碼';      return false;    }    if(isset($data['password']) && empty($data['password'])){      $this->error['msg'] = '請輸入密碼';      return false;    }    if(isset($data['headimg']) && empty($data['headimg'])){      $this->error['msg'] = '請上傳頭像';      return false;    }    return true;  }}

ProductModel 商品模型:

<?php/*** 商品模型* ProductModel.class.php* @lastmodify 2015-8-17* @author yhd*/namespace Red\Product\Models;use Think\Model;use Red\ServiceInterFace;use Red\StaticService;class ProductModel extends Model implements ServiceInterFace{  /**   * 執行個體化本類   * @return ProductModel   */  public static function getInstance() {    return StaticService::getInstance(__CLASS__);  }  /**   * 單個商品   * @param string $id   * @param integer $status 狀態 1:有效 2:無效   * @param integer $onsale 是否上架 1:是 2:否   * @return array 一維數組   */  public function getProOne($id, $status = 1 , $onsale = 1){    $condition['onsale'] = array('eq', $onsale); //是否上架    $condition['status'] = array('eq', $status); //狀態    $condition['id'] = array('eq',$id);    return $this->where($condition)->find();  }  /**   * 商品列表   * @param string $limit 查詢條數   * @param array $data 查詢條件   * @return array 二維數組   */  public function getProList($data = ''){    $condition['onsale'] = array('eq', $data['onsale']); //是否上架    $condition['status'] = array('eq', $data['status']); //狀態    $condition['type'] = array('eq', $data['type']);  //分類    if(isset($data['limit']) && isset($data['order']) ){      $return =$this->where($condition)->limit($data['limit'])->order($data['order'])->select();    }else{      $return =$this->where($condition)->select();    }    return $return;  }  /**   * 添加商品   * @param array $data   * @return int   */  public function addProduct($data){    return $this->add($data);  }  /**   * 刪除商品   *   */  public function delProduct($id){    $condition['id'] = array('eq', $id);    return $this->where($condition)->delete();  }  /**   * 修改商品   * @param string|int $id   * @param array $data   * @return   */  public function editProdcut($id, $data){    $condition['id'] = array('eq', $id);    return $this->where($condition)->save($data);  }  public function getProductInfo($product){    if(empty($product) || !isset($product['product_id'])){      return array();    }    $info = $this->getProOne($product['product_id']);    $product['name'] = $info['name'];    $product['store_id'] = $info['store_id'];    $product['price'] = $info['price'];    $product['m_price'] = $info['m_price'];    return $product;  }}

ProductManage 商品管理類:

<?php  namespace User\Controller;  use Red\Product\ProductManage;  class FavoriteController extends AuthController {  public function index($page=1){    $limit=1;    $list = ProductManage::getInstance()->getCollectList($page,$limit);    $showpage = create_pager_html($list['total'],$page,$limit);    $this->assign(get_defined_vars());    $this->display();  }  public function cancelCollect(){    $ids = field('ids');    $return = ProductManage::getInstance()->cancelProductCollect($ids);    exit(json_encode($return));  }}

functions.php 分頁函數:

<?php/** * 分頁 * @param $total 總條數 * @param $page 第幾頁 * @param $perpage 每頁條數 * @param $url 連結地址 * @param $maxpage 最大頁碼 * @return string 最多頁數*/function create_pager_html($total, $page = 1, $perpage = 20, $url = '', $maxpage = null) {  $totalcount = $total;  if (empty($url) || !is_string($url)) {    $url = array();    foreach ($_GET as $k => $v) {      if ($k != 'page') {        $url[] = urlencode($k) . '=' . urlencode($v);      }    }    $url[] = 'page={page}';    $url = '?' . implode('&', $url);  }  if ($total <= $perpage)    return '';  $total = ceil($total / $perpage);  $pagecount = $total;  $total = ($maxpage && $total > $maxpage) ? $maxpage : $total;  $page = intval($page);  if ($page < 1 || $page > $total)    $page = 1;    $pages = '<p class="pages"><a href="' . str_replace('{page}', $page - 1 <= 0 ? 1 : $page - 1, $url) . '" rel="external nofollow" title="上一頁" class="page_start">上一頁</a>';  if ($page > 4 && $page <= $total - 4) {    $mini = $page - 3;    $maxi = $page + 2;  } elseif ($page <= 4) {    $mini = 2;    $maxi = $total - 2 < 7 ? $total - 2 : 7;  } elseif ($page > $total - 4) {    $mini = $total - 7 < 3 ? 2 : $total - 7;    $maxi = $total - 2;  }  for ($i = 1; $i <= $total; $i++) {    if ($i != $page) {      $pages .= '<a class="page-num" href="' . str_replace('{page}', $i, $url) . '" rel="external nofollow" >' . $i . '</a>';    } else {      $pages .= '<span class="page_cur">' . $i . '</span>';    }    if ($maxi && $i >= $maxi) {      $i = $total - 2;      $maxi = 0;    }    if (($i == 2 or $total - 2 == $i) && $total > 10) {      $pages .= '';    }    if ($mini && $i >= 2) {      $i = $mini;      $mini = 0;    }  }  $pages .= '<a href="' . str_replace('{page}', $page + 1 >= $total ? $total : $page + 1, $url) . '" rel="external nofollow" title="下一頁" class="page_next">下一頁</a><span class="pageOp"><span class="sum">共' . $totalcount .      '條 </span><input type="text" class="pages_inp" id="pageno" value="' . $page . '" onkeydown="if(event.keyCode==13 && this.value) {window.location.href=\'' . $url . '\'.replace(/\{page\}/, this.value);return false;}"><span class="page-sum">/ ' .      $total . '頁 </span><input type="button" class="pages_btn" value="GO" onclick="if(document.getElementById(\'pageno\').value>0)window.location.href=\'' . $url . '\'.replace(/\{page\}/, document.getElementById(\'pageno\').value);"></span></p>';  return $pages;}

相關推薦:

php基於SQLite實現分頁功能的方法

PHP+Ajax實現的無重新整理分頁功能的方法

thinkPHP實現多表查詢及分頁功能的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.