thinkPHP分页功能实例详解


Posted in PHP onMay 05, 2017

本文实例讲述了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 = '<div 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></div>';
  return $pages;
}

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

PHP 相关文章推荐
PHP读写文件的方法(生成HTML)
Nov 27 PHP
PHP批量生成缩略图的代码
Jul 19 PHP
几个实用的PHP内置函数使用指南
Nov 27 PHP
yii权限控制的方法(三种方法)
Dec 28 PHP
PHP的中使用非缓冲模式查询数据库的方法
Feb 05 PHP
PHP异常处理定义与使用方法分析
Jul 25 PHP
thinkPHP5框架实现基于ajax的分页功能示例
Jun 12 PHP
PHP操作Redis数据库常用方法示例
Aug 25 PHP
ThinkPHP5.0框架验证码功能实现方法【基于第三方扩展包】
Mar 11 PHP
Laravel基础_关于view共享数据的示例讲解
Oct 14 PHP
php封装的page分页类完整实例代码
Feb 01 PHP
php7 参数、整形及字符串处理机制修改实例分析
May 25 PHP
php cli模式下获取参数的方法
May 05 #PHP
ajax调用返回php接口返回json数据的方法(必看篇)
May 05 #PHP
ThinkPHP 3.2.2实现事务操作的方法
May 05 #PHP
PHP实现Session入库/存入redis的方法
May 04 #PHP
ThinkPHP中Widget扩展的两种写法及调用方法详解
May 04 #PHP
PHP+jQuery实现滚屏无刷新动态加载数据功能详解
May 04 #PHP
PHP调用Mailgun发送邮件的方法
May 04 #PHP
You might like
基于文本的搜索
2006/10/09 PHP
ThinkPHP行为扩展Behavior应用实例详解
2014/07/22 PHP
php递归函数三种实现方法及如何实现数字累加
2015/08/07 PHP
thinkphp微信开之安全模式消息加密解密不成功的解决办法
2015/12/02 PHP
WordPress主题中添加文章列表页页码导航的PHP代码实例
2015/12/22 PHP
php自定义函数实现汉字转换utf8编码的方法
2016/09/29 PHP
PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)实例详解
2018/04/20 PHP
javascript 继承实现方法
2009/08/26 Javascript
JS 有名函数表达式全面解析
2010/03/19 Javascript
JQuery获取浏览器窗口内容部分高度的代码
2012/02/24 Javascript
jquery制作居中遮罩层效果分享
2014/02/21 Javascript
jQuery中:empty选择器用法实例
2014/12/30 Javascript
Jquery组件easyUi实现表单验证示例
2016/08/23 Javascript
JS实现DOM删除节点操作示例
2018/04/04 Javascript
Vue项目中添加锁屏功能实现思路
2018/06/29 Javascript
微信小程序如何修改本地缓存key中单个数据的详解
2019/04/26 Javascript
node.js中 redis 的安装和基本操作示例
2020/02/10 Javascript
python实现泊松图像融合
2018/07/26 Python
Python 把序列转换为元组的函数tuple方法
2019/06/27 Python
python给视频添加背景音乐并改变音量的具体方法
2020/07/19 Python
Python将字典转换为XML的方法
2020/08/01 Python
python 将html转换为pdf的几种方法
2020/12/29 Python
印度手工编织服装和家居用品商店:Fabindi
2019/10/07 全球购物
UDP协议功能
2013/01/06 面试题
写好求职信第一句话的技巧
2013/10/26 职场文书
公务员个人考察材料
2014/12/23 职场文书
事业单位工作人员年度考核个人总结
2015/02/12 职场文书
《7的乘法口诀》教学反思
2016/02/18 职场文书
HR必备:销售经理聘用合同范本
2019/08/21 职场文书
创业计划书之密室逃脱
2019/11/08 职场文书
Windows安装Anaconda3的方法及使用过程详解
2021/06/11 Python
Python 数据科学 Matplotlib图库详解
2021/07/07 Python
基于Redis结合SpringBoot的秒杀案例详解
2021/10/05 Redis
Python中如何处理常见报错
2022/01/18 Python
人物搭配车车超萌联名预备中 【咒术迴战】 ⨯ 【天竺鼠车车】 展开合作
2022/04/11 日漫
Golang 链表的学习和使用
2022/04/19 Golang