PHP pagination Class [ more advanced ]

A more advanced pagination class.
Css classes / Text links are editable.
PHP >5 ONLY!

<?php

/**
 * Pagination Class
 *
 * @author		Paolo Mulder
 * @copyright	Copyright (c) 2011, Paolo mulder
 * @contact		paolo.mulder@gmail.com
 */
// ------------------------------------------------------------------------

class Pagination {
	
	private 	$debug;
	public		$limit;
	public		$base_url;
	private		$page_tag;
	public		$page;
	public		$total_items;
	private		$max_pages;
	public		$links_on_page;


	//css Classes.
	private		$classFirstPage;
	private		$classLastPage;
	private		$classNumbers;
	private		$classNextPage;
	private		$classPrevPage;
	private		$classCurrentPage;
	private		$classSelected;
	private		$classAppend;
	
	//Link texts.
	private		$txtFirstPage;
	private		$txtLastPage;
	private		$txtCurrentPage;// Needs following tags [current] && [last]
	private		$txtNextPage;
	private		$txtPrevPage;
	
	
  function __construct( $debug=false ) {
  	
  		$this->debug	=$debug;
		
		##default Limit
		$this->limit =20;
		
		## Set default css classes.
		$this->classFirstPage	='first-page';
		$this->classLastPage	='last-page';
		$this->classNumbers	='numbers-page';
		$this->classNextPage	='next-page';
		$this->classPrevPage	='prev-page';
		$this->classCurrentPage	='current-page';
		
	
		## Set default link (pages ) texts.
		$this->txtFirstPage		='First';
		$this->txtLastPage		='Last';
		$this->txtCurrentPage	        ='[current] of [last] ';
		$this->txtNextPage		='Next';
		$this->txtPrevPage		='Previous';
		
		// Set default url/tag
		$this->base_url			='http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		$this->page_tag			='p=';// Set get var for pages: page- , Page etc.{ page-1,Page1}
		
		$this->page			='1'; // current page.
		$this->total_items		=false;
		$this->max_pages		=false;
		
		# how many (number) links on page ? ( 1 t/m 10 == 10  )
		# set default @ 10.
		$this->links_on_page		=10;
  	
  }
  
/* ===================================================================================== 

	Setting /Overwriting needed variables.

========================================================================================*/  
  
  	/*
		Overwrite default limit
	
	*/
  	public function setLimit ( $limit ){
			
		$this->limit	=$limit;
	}
  
  	/*
		Set current page 
	*/	
  	public function setPage ( $page =1 ){
		
		$this->page		=$page;
	
	}
	
	/*
		Set total items/rows 
	*/	
  	public function setTotalItems ( $total ){
		
		$this->total_items	=$total;
		
	
	}
  
	/*
		Overwrite default base_url
	
	*/
	public function setBaseUrl( $url ){
	
		$this->base_url	=$url;
	
	}
	
	
	/*
		Overwrite  default page tag 
		e.g. : p= / page- / Page 
		Example url:
		domain/Page1/
		domain/?p=1
		domain/artitcletitle-page-1/
	
	*/
	public function setPageTag( $tag ){
	
		$this->page_tag	=$tag;
	
	}
	
	/*
		Overwrite default links per page
		Default =10;
		Number of links , 1 t/m 10 pages = 10
		
	*/
	public function setLinksOnPage( $number ){
	
		$this->links_on_page	=$number;
	
	}
	
	
	/*
		Set max_pages,
	
	*/
	
	private function setMaxPages (){
		
		if( $this->max_pages )
			return false;
			
		$this->max_pages	=ceil($this->total_items / $this->limit );
		
	
	}

/* ===================================================================================== 

	Function creating the actual links

========================================================================================*/



	
	/*
		Check needed Vars to Proceed.
	
	*/
	private function checkVars(){

		if( $this->limit < 1 ){
			$this->notice(__METHOD__.' Limit is set below 1 item per/page.' );
			return false;
		}
		
		if( $this->total_items < 1 ){
			$this->notice(__METHOD__.' Not enough Items/Rows To output pages' );
			return false;
			
		}
		
		if( $this->total_items <= $this->limit ){
			$this->notice(__METHOD__.' Not enough Items/Rows To output pages' );
			return false;
			
		}
		
		## reset appended classes.
		$this->classAppended =false;
		
		return true;
		
	}
	
	/*
		Create page Url
	
	*/
	private function createUrl( $page ){
	
		$url 	='ERROR_RUN_DEBUG';
		
		## is the baseUrl  valid ?
		if( !preg_match('/www|http/i',$this->base_url) )
			$this->notice(" BASE_URL not valid ! ". $this->base_url);
			
		##page tag present?	
		if( !$this->page_tag )
			$this->notice(" PAGE TAG nog valid ! ");
			
		## current page present?	
		if( !$page )
			$this->notice(__METHOD__." PAGE not valid ! ");
			
		## GET var or Mod Rewrite Url ( /page1/ ) ?
		# rewrite url with needed link page.
		if( preg_match('/=/',$this->page_tag ) ){
			$url	=preg_replace('/(\?|&)?'.$this->page_tag.'\d{1,100}/','',$this->base_url );
			if( preg_match('/=/',$url) )
				$url	=$url.'&'.$this->page_tag.$page;
			else	
				$url	=$url.'?'.$this->page_tag.$page;
		}
		else{
			## mod rewrite pages.
			## Not very good , need to rewrite it with a better function.
			if( preg_match('/'.str_replace('/','\/',$this->page_tag).'/i',$this->base_url ) )
				$url	=preg_replace('/'.str_replace('/','\/',$this->page_tag).'\d{1,100}/','$1'.$this->page_tag.$page,$this->base_url );
			else
				$url	=$this->base_url.$this-page_tag.page;
		}
		
		
		
		return $url;
	
	}
	
	/*
		Create Href link
	
	*/
	private function createLink( $url , $class, $txt ,$selected ){
		
		$link	='<a ';
		$link	.='href="'.$url.'" ';
		if( !$selected )
			$link	.='class="'.$class.'" >';
		else
			$link	.='class="'.$class.' '.$this->classSelected.'" >';
		$link	.=$txt;
		$link	.='</a>';
		
		return $link;

	}
	
	
	
/* ===================================================================================== 

	Rendering Pages links.

========================================================================================*/


	
	/*
		First Page.
	*/
	
	public function renderFirst(){
		if( !$this->checkVars() )
			return false;
		
		#selected?	
		if( $this->page ==1 )
			$this->classAppended	=true;
			
		##create && return link
		return $this->createLink( $this->createUrl( 1 ),
					  $this->classFirstPage,
					  $this->txtFirstPage,
					  $this->classAppended );
		
	
	}
	
	
	/*
		Last Page.
	*/
	
	public function renderLast(){
		if( !$this->checkVars() )
			return false;
			
		## set max pages ( if not already set).
		$this->setMaxPages();
		
		#selected ?
		if( $this->page == $max_pages )
			$this->classAppended	=true;
			
		##create && return link
		return $this->createLink( 	$this->createUrl( $this->max_pages ),
									$this->classLastPage,
									$this->txtLastPage,
									$this->classAppended );
		
	
	}
	
	
	/*
		Next page
	*/
	
	public function renderNext(){
		if( !$this->checkVars() )
			return false;
			
		## set max pages ( if not already set).
		$this->setMaxPages();
		
		##create && return link
		if ($this->page < $this->max_pages )
			return $this->createLink( 	$this->createUrl( $this->page +1 ),
										$this->classNextPage,
										$this->txtNextPage,
										false 				);
		
		else	
			return false;
		
	
	}
	
	
	/*
		Prevous page
	*/
	
	public function renderPrev(){
		if( !$this->checkVars() )
			return false;
		
		##create && return link
		if ($this->page > 1 )
			return $this->createLink( 	$this->createUrl( $this->page -1 ),
										$this->classPrevPage,
										$this->txtPrevPage,
										false 				);
		
		else	
			return false;
		
	
	}
	
	
	/*
		Render number pages 
	
	*/
	public function renderNumbers(){
	
		if( !$this->checkVars() )
			return false;
			
		## check if number of links is valid
		if ( $this->links_on_page < 1 )
			return false;
			
		## set max pages ( if not already set).
		$this->setMaxPages();	
		
		## Caculate pages for links.
		$split	=ceil( $this->links_on_page / 2 );
		$start	=$this->page - $split;
		$end	=$this->page + $split;
		if( $start < 1 || $end > $this->max_pages ){
		
			$batch	=	ceil( $this->page / $this->links_on_page );
			$end	=	$batch * $this->links_on_page;
			if( $end  > $this->max_pages )
			$end	=$this->max_pages;
			
			$start	=( $end	- $this->links_on_page ) +1;
			if( $start < 1 )
				$start =1;
		}
			
		
		##Loop and create links.
		$links 	='';
		
		for($i = $start; $i <= $end; $i ++) {
		
			## current page.
			if( $i == $this->page )
				$links	.=$this->createLink( 	$this->createUrl( $i ),
												$this->classCurrentPage,
												$this->currentName(),
												false 				
											);	
				
			## create numbers							
			else
				$links	.=$this->createLink( 	$this->createUrl( $i ),
												$this->classNumbers,
												$i,
												false 				
											);	
			
		}
				
		if(strlen($links) > 0 )
			return $links;
		else
			return false;
	
	}
	
	/*
		Create special Text for current page on number links
	
		example : 
		current page = 1  && total pages = 10
		output = 1 of 10  ( on default $this->txtCurrentPage )
		
	*/
	private function currentName (){
		$link_name	='';
		
		## set max pages ( if not already set).
		$this->setMaxPages();	
		
		#replace [current] with current page.
		$link_name	=preg_replace('/\[current\]/i',$this->page,$this->txtCurrentPage);
		
		#replace [last] with total pages 
		$link_name	=preg_replace('/\[last\]/i',$this->max_pages,$link_name);
		
		
		return $link_name;
	}


	/*
		Render complete page set.
		@param prefix : wrapper around page link elements.
		@param suffix : end wrapper tag.
		@param numbers : show numbers ? 
		@param first_last   : show first/next ?
	
	*/
	
	public function renderPageSet( $prefix ='<div class="pages">', $suffix='</div>', $numbers=true , $first_last =true ){
	
		if( !$this->checkVars() )
			return '';
	
		$string	=$prefix;
	
		# create first button
		if( $first_last )
			$string	.=$this->renderFirst();
		
		# create previous button
		$string	.=$this->renderPrev();
		
		#create numbers
		if( $numbers )
			$string	.=$this->renderNumbers();
		
		#create next button	
		$string .=$this->renderNext();
		
		#create last button.
		if( $first_last )
			$string.=$this->renderLast();
			
		$string.=$suffix;
	
		return $string;
	}





/* ===================================================================================== 

	Overwriting Default variables [ classes/ text ] links.

========================================================================================*/


  
  /*
  	Overwrite defaults css Classes
 
  */

	public function setClassFirstPage( $class ){
		
		$this->classFirstPage	=$class;
		
	}  
	
	public function setClassLastPage( $class ){
		
		$this->classLastPage	=$class;
		
	}  
	
	
	public function setClassNumbers( $class ){
		
		$this->classNumbers	=$class;
		
	}  
	
	
	public function setClassNextPage( $class ){
		
		$this->classNextPage	=$class;
		
	}  
	
	public function setClassPrevPage( $class ){
		
		$this->classPrevPage	=$class;
		
	}  
	
	
	public function setClassCurrentPage( $class ){
		
		$this->classCurrentPage	=$class;
		
	}  
	
	## will be appended to the classes above if selected.
	public function setClassSelected( $class ){
		
		$this->classSelected	=$class;
		
	}  
	
	
	/*
  	Overwrite defaults link texts.
 
  */

	public function setTxtFirstPage( $txt ){
		
		$this->txtFirstPage	=$txt;
		
	}  
	
	public function setTxtLastPage( $txt ){
		
		$this->txtLastPage	=$txt;
		
	}  
	
	## needs tags [current] && [last]
	## Example : 23 of 100 Pages
	## @param $txt = [current] of [last] Pages
	
	public function setTxtCurrentPage( $txt ){
	
		if( !preg_match('/\[current\]/i',$txt) )
			$this->notice(__METHOD__.' NEED [current] TAG in text');
		
		if( !preg_match('/\[last\]/i',$txt) )
			$this->notice(__METHOD__.' NEED [last] TAG in text');
		
		$this->txtCurrentPage	=$txt;
		
	}  
	
	
	public function setTxtNextPage( $txt ){
		
		$this->txtNextPage	=$txt;
		
	}  
	
	public function setTxtPrevPage( $txt ){
		
		$this->txtPrevPage	=$txt;
		
	}  
  
  
  /*
  	Notice debug.
  */
	public function notice ( $msg ){
		if( !$this->debug )
			return false;
			
		echo '<hr>';
		echo $msg;
		echo '<hr>';
	
	}
	
}




?>

Usage

Just copy into a php page for debug.
Enjoy !








Example Pagination Class



/* Example stylesheet with default classes */

a{
color:#2786C2;
font-size:14px;
font-weight:bold;

}

div.pages {
width:900px;
margin:0 auto;
margin-top:15px;
margin-bottom:20px;
}

.first-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:20px;

}

.next-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:20px;

}



.prev-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:20px;

}

.numbers-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:10px;

}

.current-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:10px;


}

.last-page{
float:left;
padding:5px 10px 5px 10px;

margin-right:10px;

}

/* clear floats from above */
.clear { clear:both;}

/*
some colors to try out
*/
.blue { color:#2786C2; }
.black { color:#2C2C2C; }
.red { color:#A60000; }
.grey-light { color:#F4F4EE; }
.grey { color:#888884; }
.green { color:#97BB1B; }
.grey_menu { color:#E7E7DE; }
.white { color:#FFFFFF; }

.bg_blue { background-color:#2786C2; }
.bg_black { background-color:#2C2C2C; }
.bg_red { background-color:#A60000; }
.bg_grey-light { background-color:#F4F4EE; }
.bg_grey { background-color:#888884; }
.bg_green { background-color:#97BB1B; }
.bg_grey_menu { background-color:#E7E7DE; }
.bg_white { background-color:#FFFFFF; }


Comments

paolo_mulder
Posted on 13.03.2011 17:13

// usage

// Unqiue page elements
$pag->notice(' Unqiue elements ');

?>
<?=$pag->renderFirst();?>


<?=$pag->renderPrev();?>


<?=$pag->renderNumbers();?>


<?=$pag->renderNext();?>


<?=$pag->renderLast();?>



<?php
// Full pagination in one function
$pag->notice(' Full pagination function ');
?>

<?=$pag->renderPageSet();?>





<?php
/*
Customize full Pageset
$prefix = start wrapper tag
$suffix = end wrapper tag
*/
$pag->notice(' Full pagination function costumized ');

$prefix ='';
$suffix ='';

/*
show numbers ? default=true
*/
$numbers =false;

/*
Show First/Last ? default =true

*/

$first_last=false;

// Render customized Pageset.
echo $pag->renderPageSet( $prefix , $suffix , $numbers , $first_last );


?>



<?php
// Extra vars in url ? not a problem.
$pag->notice(' Extra vars in url ? no problem : Example ');
?>

paolo_mulder
Posted on 13.03.2011 17:13

OK the usage just stripped every bit of php code.


/*
Example Pagination Class


#Needed vars :

setPage = get current page indication from $_GET
setTotalItems = Total number of rows or items.

*/

#load class.
$path ='';
require_once($path.'pagination.class.php');
$pag =new Pagination( true ); // true = debug ;

$pag->setPage( ($_GET['p']) ? $_GET['p']:1 );
$pag->setTotalItems ( 500 );
$pag->setLimit ( 10 ); #number of items per page ( default = 20 )

/*
Customizing Pagination:
remove # comment to see the effect.
*/

// Changing number of items/rows per page.
// Default = 20
#$pag->setLimit ( 25 );


// Changing page tag for the GET var.
// Default : p=
#$pag->setPageTag( 'page=' );
#$pag->setPage( ($_GET['page']) ? $_GET['page']:1 );

// Changing the number of links (numbers) on page
// Default = 10
#$pag->setLinksOnPage ( 15 );


// Changing css classes
// add a css class below ( stylesheet) and try it out.
// Multiple classes can be applied like shown in the example below.
// Each element can have a different class.
#$pag->setClassPrevPage('prev-page bg_grey-light');
#$pag->setClassNextPage('next-page bg_grey-light');
#$pag->setClassNumbers('numbers-page bg_grey-light');
#$pag->setClassCurrentPage('current-page bg_grey-light green');
#$pag->setClassLastPage('current-page bg_grey-light green');
#$pag->setClassFirstPage('current-page bg_grey-light green');

// Changing text of links
#$pag->setTxtPrevPage('Vorige');
#$pag->setTxtNextPage('Volgende');
#$pag->setTxtCurrentPage("[current] van [last] pagina's");
#$pag->setTxtLastPage('Laatste');
#$pag->setTxtFirstPage('Eerste');


// Redering full pagination also can be customized.
// See end of page.

Add your comment