Un semplice esempio:
Codice PHP:
<?php
class Pager{
private $numRecs;
private $totalRecs;
public $output;
public function __construct($dataFile,$numRecs=5){
(file_exists($dataFile)&&count(file($dataFile))>0)?$this->totalRecs=array_reverse(file($dataFile)):die('Data file not valid.');
// validate number of records per page
(is_int($numRecs)&&$numRecs>0)?$this->numRecs=$numRecs:die('Invalid number of records'.$numRecs);
}
public function displayRecords($getIndex){
$page=isset($_GET[$getIndex])?$_GET[$getIndex]:0;
// calculate number of pages
$numPages=ceil(count($this->totalRecs)/$this->numRecs);
// validate page pointer
if(!preg_match("/^\d{1,2}$/",$page)||$page<1||$page>$numPages){
$page=1;
}
// retrieve corresponding records from flat file
$records=array_slice($this->totalRecs,($page-1)*$this->numRecs,$this->numRecs);
foreach($records as $row){
$columns=explode('|',$row);
foreach($columns as $column){
$this->output.=$column.'';
}
$this->output.='
';
}
// create previous link
if($page>1){
$this->output.='[url="'.$_SERVER['PHP_SELF'].'?page='.($page-1).'"]<<Previous[/url]';
}
// create intermediate links
for($i=1;$i<=$numPages;$i++){
($i!=$page)?$this->output.='[url="'.$_SERVER['PHP_SELF'].'?page='.$i.'"]'.$i.'[/url]':$this->output.=$i.'';
}
// create next link
if($page<$numPages){
$this->output.='[url="'.$_SERVER['PHP_SELF'].'?page='.($page+1).'"]Next>>[/url] ';
}
// return final output
return $this->output;
}
}
$paging = new Pager('data.dat');
echo $paging->displayRecords('page');
?>
il file data.dat
Codice PHP:
Chariots of fire|Vangelis
Friends of Mr. Cairo|Vangelis
Lucifer|The Alan Parson Project
The eye in the sky|Alan Parson Project
Caribean Blue|Enya
Only Time|Enya
Music|John Miles
The turn of a friendly card|The Alan Parson Project
Children|Robert Miles
One and One|Robert Miles
Sadness|Enigma
Mea Culpa|Enigma
Cherry Blossom Girl|Air
Hot stuff|Donna Summer
Bad Girls|Donna Summer
I will survive|Gloria Gaynor
Rimes and reasons|John Denver
Touch and go|Emerson,Lake and Powell
In Jeopardy|Roger Hogdson
Ameno|Era
Il workhorse è la funzione array_slice