Home Backend Development PHP Tutorial 非常好用的Zend Framework分页类_PHP

非常好用的Zend Framework分页类_PHP

Jun 01, 2016 am 11:51 AM

在这里和大家分享一个非常好用的 Zend Framework 分页类
 
具体效果可见本站的分页效果, CSS样式可根据个人设计感进行更变。
 

这里我会举例演示如何使用该类, 如下:
 
IndexController.php, 在 Action 中写入如下代码:
复制代码 代码如下:
protected  $_curPage = 1;      //默认第一页
const PERPAGENUM     = 4;      //每页显示条目数
 
public function indexAction()
{  
    // $this->_blogModel 已实例化 blog Model
    // $rows -> 获得到所展示数据的总条目数
    $rows = $this->_blogModel->getTotalRows();
     
    if($pageNum = $this->getRequest()->getParam('page')) {
        //如果有值传入,覆盖初始的第一页
        $this->_curPage = $pageNum;
    }
     
    //把数据表中的数据传到前端
    $this->view->blogInfo = $this->_blogModel->getBlogInfo(
                                self::PERPAGENUM, ($this->_curPage-1)*self::PERPAGENUM
                            );
    //实例化分页类,并传到前端
    $this->view->pagebar = $this->displayPageBar($rows);
}
 
private function displayPageBar($totalRows)
{
    $Pager = new Zend_Pagination($totalRows,self::PERPAGENUM);
    return $Pager->getNavigation();
}

models/Blog.php,写入如下代码:
复制代码 代码如下:
public function getBlogInfo($perPageNum = NULL, $limit = NULL)
{
    return $this->fetchAll('1 = 1', 'blog_id desc', $perPageNum, $limit)
                ->toArray();
}
 
public function getTotalRows($where = '1=1')
{
    return $this->fetchAll($where)->count();
}

index.phtml, 写入如下代码:
复制代码 代码如下:


    pagebar; ?>

到这里,就可以看见效果了, 如想追求更好的页面效果, 请根据个人喜好修改分页类,这里就不作详细示例
复制代码 代码如下:
class Zend_Pagination
{
    private $_navigationItemCount = 6;        //导航栏显示导航总页数
    private $_pageSize            = null;     //每页项目数
    private $_align               = "right";  //导航栏显示位置
    private $_itemCount           = null;     //总项目数
    private $_pageCount           = null;     //总页数
    private $_currentPage         = null;     //当前页
    private $_front               = null;     //前端控制器
    private $_PageParaName        = "page";   //页面参数名称
 
    private $_firstPageString     = "|     private $_nextPageString      = ">>";     //导航栏中前一页显示的字符
    private $_previousPageString  = "     private $_lastPageString      = ">>|";    //导航栏中最后一页显示的字符
    private $_splitString         = " | ";    //页数字间的间隔符
 
    public function __construct($itemCount, $pageSize)
    {
        if (!is_numeric($itemCount) || (!is_numeric($pageSize))) {
            throw new Exception("Pagination Error:not Number");
        }
        $this->_itemCount = $itemCount;
        $this->_pageSize  = $pageSize;
        $this->_front     = Zend_Controller_Front::getInstance();
 
        $this->_pageCount = ceil($itemCount/$pageSize);   //总页数
        $page = $this->_front->getRequest()->getParam($this->_PageParaName);
         
        if (empty($page) || (!is_numeric($page))) {  
            //为空或不是数字,设置当前页为1
            $this->_currentPage = 1;
        } else {
            if ($page                 $page = 1;
            }
            if ($page > $this->_pageCount) {
                $page = $this->_pageCount;
            }
            $this->_currentPage = $page;
        }
    }
 
    public function getCurrentPage()
    {
        return $this->_currentPage;
    }
 
    public function getNavigation()
    {
        $navigation = '

';
         
        //当前页处于第几栏分页
        $pageCote      = ceil($this->_currentPage / ($this->_navigationItemCount - 1)) - 1;  
        //总分页栏
        $pageCoteCount = ceil($this->_pageCount / ($this->_navigationItemCount - 1));
        //分页栏中起始页
        $pageStart     = $pageCote * ($this->_navigationItemCount -1) + 1; 
        //分页栏中终止页      
        $pageEnd       = $pageStart + $this->_navigationItemCount - 1;                      
         
        if($this->_pageCount             $pageEnd   = $this->_pageCount;
        }
         
        $navigation .= "总共: {$this->_itemCount} 条 共 {$this->_pageCount} 页\n  ";
         
        if($pageCote > 0) {           //首页导航
            $navigation .= '$this->_firstPageString ";
        }
        if($this->_currentPage != 1) {       //上一页导航
            $navigation .= '$this->_previousPageString ";
        }else{
            $navigation .= $this->_previousPageString . ' ';
        }
        
        while ($pageStart         {
            if ($pageStart == $this->_currentPage) {
                $navigation .= "$pageStart" . $this->_splitString;
            } else {
                $navigation .= '$pageStart"
                               . $this->_splitString;
            }
            $pageStart++;
        }
         
        if($this->_currentPage != $this->_pageCount) {   //下一页导航
            $navigation .= ' $this->_nextPageString ";
        }else{
            $navigation .= $this->_nextPageString;
        }
        
        if ($pageCote             $navigation .= '$this->_lastPageString ";
        }
 
        $navigation .= ' 到 ';
        $navigation .= " 页
";
        return $navigation;
    }
 
    public function getNavigationItemCount()
    {
        return $this->_navigationItemCount;
    }
 
    public function setNavigationItemCoun($navigationCount)
    {
        if(is_numeric($navigationCount)) {
            $this->_navigationItemCount = $navigationCount;
        }
    }
 
    public function setFirstPageString($firstPageString)
    {
        $this->_firstPageString = $firstPageString;
    }
 
    public function setPreviousPageString($previousPageString)
    {
        $this->_previousPageString = $previousPageString;
    }
 
    public function setNextPageString($nextPageString)
    {
        $this->_nextPageString = $nextPageString;
    }
 
    public function setLastPageString($lastPageString)
    {
        $this->_lastPageString = $lastPageString;
    }
 
    public function setAlign($align)
    {
        $align = strtolower($align);
        if ($align == "center") {
            $this->_align = "center";
        } elseif ($align == "right") {
            $this->_align = "right";
        } else {
            $this->_align = "left";
        }
    }
    
    public function setPageParamName($pageParamName)
    {
        $this->_PageParaName = $pageParamName;
    }
 
    public function getPageParamName()
    {
        return $this->_PageParaName;
    }
 
    private function createHref($targetPage = null)
    {
        $params     = $this->_front->getRequest()->getParams();
        $module     = $params["module"];
        $controller = $params["controller"];
        $action     = $params["action"];
 
        $targetUrl = $this->_front->getBaseUrl()
                     . "/$module/$controller/$action";
                      
        foreach ($params as $key => $value)
        {
            if($key != "controller" && $key != "module"
               && $key != "action" && $key != $this->_PageParaName) {
                $targetUrl .= "/$key/$value";
            }
        }
        if (isset($targetPage)) {                //指定目标页
            $targetUrl .= "/$this->_PageParaName/$targetPage";
        } else {
            $targetUrl .= "/$this->_PageParaName/";
        }
        return $targetUrl;
    }
}

这里再简单回顾下 Mysql 中的 limit offset
 
假设数据库表 blog 存在 13 条数据。

语句1:select * from blog limit 9, 4
语句2:select * from blog limit 4 offset 9

//语句1和2均返回表 blog 的第 10、11、12、13 行
//语句1中的 9 表示从表的第十行开始, 返回 4 行
//语句2中的 4 表示返回 4 行,offset 9 表示从表的第十行开始

如下语句显示分页效果:

语句3:select * from blog limit ($this->_curPage - 1)* self::PERPAGENUM, self::PERPAGENUM;
语句4:select * from blog limit self::PERPAGENUM offset ($this->_curPage - 1) * self::PERPAGENUM;

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles