Pagerクラスを書いてみた

意外と面倒なページング処理。
簡素すぎてこれでいいのかわからないけど、
簡単なページングならこれが使えると思う。

<?php

class Pager{
  public $allpage = '';
  public $n = '';
  public $url = '';
  protected $p= '';

  public function __construct($c)
  {
    if(!empty($c)){
      $this->allpage = $c;
      $this->url = htmlspecialchars($_SERVER['REQUEST_URI']);
    }else{
      die('set data!');
    }
  }

  public function page_number($num)
  {
     $divn = count($this->allpage) / $num;
     $this->p = $num;
     if(is_float($divn)){
       $this->n = (int)round($divn);
     }else{
       $this->n = $divn;
     }
  }

  public function page_navi($url)
  {
    $format = '<ul>';
    $now = $this->now_page();
    $n = 1;
    $format.= $this->prev($url);
    for($i=0;$i<$this->n;$i++){
       if($n == $now){
         $format.='<li>'.$n.'</li>';
       }else{
         $format.='<li><a href="'.$url.$n.'">'.$n.'</a></li>';
       }
       $n++;
    }
    $format.= $this->next($url);
    $format.='</ul>';
    return $format;
  }

  public function now_page()
  {
    $pat = "/(\d$)/";
    preg_match($pat,$this->url,$mat);
    return $mat[0];
  }

  public function prev($url)
  {
    $now = $this->now_page();
    $prev_page = --$now;
    $prev = '<li><a href="'.$url.$prev_page.'">&lt;</a></li>';
    if($prev_page>0){
      return $prev;
    }
  }

  public function next($url)
  {
    $now = $this->now_page();
    if($now<$this->n){
      $next_page = ++$now;
      $next = '<li><a href="'.$url.$next_page.'">&gt;</a></li>';
      return $next;
    }
  }

  public function content()
  {
    $n = $this->now_page();
    $nn = $n * $this->p;

    if($n == '1'){
      for($i=0;$i<$this->p;$i++){
         echo($this->allpage[$i]);
         echo('<br>');
      }
    }else{
      for($i=$nn-$this->p;$i<$nn;$i++){
         echo($this->allpage[$i]);
         echo('<br>');
      }
    }
  }
}

以下のように使う。
必要ならdivで囲ったりclassとかidをつければそれなりにレイアウトも調整できるね!

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja-JP" lang="ja-JP">
<head>
<style type="text/css">
ul{
list-style:none;
}

li{
padding:0 0 0 10px;
float:left;
}
</style>
</head>

<body>
<?php

require_once('Pager.php');

$content = array(
           '1',
           '2',
           '3',
           '4',
           '5',
           '6',
           '7'
           );

$p = new Pager($content);
$p->page_number(2);//何件表示させるか
$m = $p->page_navi('p.php?category=1&p=');
$p->content();
echo($m);
?>

</body>
</html>

$contentに実際のデータを入れて、
あとは表示件数を指定する。