Scripts

Paginanummering Klasse

-- Helemaal gewijzigd! Na geluisterd te hebben naar de kritiek die ik kreeg, heb ik de vorige hele klasse opgedeeld in 3 kleinere klassen, waarbij alles wat bij elkaar hoort bij elkaar zit. Alles spreekt nog voor zich. setCurrentStringRegex($regex, $replace) Zet de regex waarin het huidige paginanummer moet komen te staan. Geef als tweede parameter op wat gereplaced moet worden met iCurrent (het huidige paginanummer). setToStringRegex($regex, $replaceArray) Zet de regex waarin de paginanummers moeten komen te staan. Het huidige paginanummer zit in getNumbers(), dus daar hoef je je hier niet druk om te maken. De rest spreekt denk ik wel voor zich. setWord($engels, $nederlands) Zet de woorden eerste, vorige, volgende en laatste. De Engelse woorden moeten altijd zo zijn als ze in het voorbeeld staan! Als je die veranderd wordt jouw tekst niet gebruikt. Die zijn alleen om aan te geven welk woord je wil vervangen. NavigationDatabase::getQueryResult($query) Hoef je niet per sé te gebruiken. Je kunt hier ook gewoon je eigen query en query behandeling zetten. Het is alleen een voorbeeld dat dit ook mogelijk is. Echo'en van $oPagination, in dit geval de beginvariabele van de klasse, weergeeft de paginanummering al. Dus geen toString() functie meer. Let wel even op de volgorde dat hij hieronder in het voorbeeld staat. De CurrentRegex moet namelijk altijd vóór de StringRegex gedefinieerd worden. De QueryTable, WhereStatement of de hele query moeten altijd vóór doExecute() gedefinieerd zijn. En voordat je $oPagination gaat echo'en moeten alle behandelingen die je wilt doen gedaan zijn. Ik hoop dat hij iets toevoegt! - Jezpur Overzichtelijker voorbeeld (met code).

paginanummering-klasse
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);

// <title>Navigatie Klasse</title>

include("phphulp/config.php");


class Navigation {
	// current page, total pages and pagination pages amount.
	protected $iCurrent;
	protected $iTotal;
	
	// limitation vars
	protected $iStart;
	protected $iShowRecords;
	protected $iShowNumbers;
	
	// query vars by using setQuery and setQueryCountField()
	protected $sCountQuery;
	protected $sQueryCountField = 'aantal';
	
	// query vars by using setQueryTable and setQueryWhereStatement()
	protected $sTable;
	protected $sWhereStatement;
	
	// parameter var
	protected $sGetParameter;
	
	// output vars
	protected $aPagination = array();
	protected $aToStringReplacements = array();
	protected $aWords = array('first'=>'First','prev'=>'Previous','next'=>'Next','last'=>'Last');
	protected $sToStringRegex;
	protected $aToCurrentReplacements = array('[*c]', '*c');
	protected $sSpace = '...';
	
	// construction
	public function __construct($iCurrent, $iShowRecords = 20, $iShowNumbers = 6, $sGetParameter) {
		$this->iCurrent = ($iCurrent > 1) ? (int)$iCurrent : 1;
		$this->iShowRecords = ($iShowRecords > 0) ? (int)$iShowRecords : 20;
		$this->iShowNumbers = ($iShowRecords > 0) ? (int)$iShowNumbers : 6;
		$this->iStart = ($iCurrent-1) * $iShowRecords;
		$this->sGetParameter = (string)trim($sGetParameter);
	}
	
	public function setCurrentStringRegex($sRegex, $sReplace) {
		$this->aToCurrentReplacements = array($sRegex, $sReplace);
	}
	
	// set style for the toString function.
	public function setToStringRegex($sRegex, $aReplacements) {
		$this->sToStringRegex = (string)trim($sRegex);
		$this->aToStringReplacements = $aReplacements;
	}
	
	// set ...
	public function setSpace($sString) {
		$this->sSpace = (string)trim($sString);	
	}
	
	// set words, first, next, previous, last.
	public function setWord($sEnglishWord, $sWord) {
		if($sEnglishWord == 'first') {
			$sArrayKey = 'first';		
		} else {
			$sArrayKey = substr($sEnglishWord, 0, 4);
		}
		
		$this->aWords[$sArrayKey] = trim($sWord);
	}
	
	// fill array and vars
	public function doExecute() {
		$oDatabase = new NavigationDatabase($this);
		
		if(empty($this->sCountQuery)) {
			if(!empty($this->sTable)) {
				$oDatabase->createQuery();
			} else {
				throw new Exception('First enter a table to be searched in.');
			}
		}
		
		$oDatabase->calculateTotalPages();
		$this->setNavigation();	
	}
	
	// set next page in the pagination array.
	protected function setNext() {
		if($this->iCurrent == $this->iTotal) {
			$this->aPagination['next'] = false;
		} else {
			$this->aPagination['next'] = $this->iCurrent+1;
		}
	}
	
	// set last page in the pagination array.
	protected function setLast() {
		if($this->iCurrent == $this->iTotal) {
			$this->aPagination['last'] = false;
		} else {
			$this->aPagination['last'] = $this->iTotal;
		}
	}
	
	// set previous page in the pagination array.
	protected function setPrevious() {
		if($this->iCurrent <= 1) {
			$this->aPagination['prev'] = false;
		} else {
			$this->aPagination['prev'] = $this->iCurrent-1;
		}
	}
	
	// set first page in the pagination array.
	protected function setFirst() {
		if($this->iCurrent <= 1) {
			$this->aPagination['first'] = false;
		} else {
			$this->aPagination['first'] = 1;
		}
	}
	
	// set points in the pagination array.
	protected function setSpaces() {
		$iNumbersRound = ceil($this->iShowNumbers / 2);
		
		if(($this->iCurrent - $iNumbersRound) <= 1) {
			$this->aPagination['space_before'] = false;
		} else {
			$this->aPagination['space_before'] = $this->sSpace;
		}
		
		if(($this->iCurrent + $iNumbersRound) >= $this->iTotal) {
			$this->aPagination['space_after'] = false;
		} else {
			$this->aPagination['space_after'] = $this->sSpace;
		}
	}
	
	// set the pagination numbers in the pagination array.
	protected function setNumbers() {
		$iNumbersRound = floor($this->iShowNumbers / 2);
		
		$iStart = ($this->iCurrent - $iNumbersRound) <= 1 ? 1 : ($this->iCurrent - $iNumbersRound);
		$iEnd = ($this->iCurrent + $iNumbersRound) >= $this->iTotal ? $this->iTotal : ($this->iCurrent + $iNumbersRound);
		
		for($i=$iStart;$i<=$iEnd;$i++) {
			if($i == $this->iCurrent)
				$this->aPagination['current'] = $i;
			
			$this->aPagination['numbers'][] = $i;
		}
	}
	
	// set everything by using the six functions above.
	protected function setNavigation() {
		$this->setFirst();
		$this->setLast();
		$this->setNext();
		$this->setPrevious();
		$this->setSpaces();
		$this->setNumbers();
	}
	
	// zip everything to a string, can be used by the inexperienced programmer.
	// there is also an expert version; use the stringReplacement methods to set up your own style.
	public function __toString() {
		if(!empty($this->sToStringRegex)) {
			$sString = $this->sToStringRegex;
			foreach($this->aToStringReplacements as $sRegex => $sReplace) {
				$sString = str_replace($sRegex, $sReplace, $sString);
			}
		} else {
			$aPags = NavigationOutput::getNavigation();
			$sString = '';
			
			if(is_bool(NavigationOutput::getFirst()))
				$sString .= $aWords['first'];
			else
				$sString .= '<a href="?'.$this->sGetParameter.'='.$aPags['first'].'">'.$aWords['first'].'</a> | ';
			
			if(is_bool(NavigationOutput::getPrevious()))
				$sString .= $aWords['prev'];
			else
				$sString .= '<a href="?'.$this->sGetParameter.'='.$aPags['prev'].'">'.$aWords['prev'].'</a> | ';
			
			$sString .= NavigationOutput::getSpaceBefore();
			
			foreach($aPags['numbers'] as $iNum) {
				if($iNum == NavigationOutput::getCurrent()) {
					$sString .= ' ['.$iNum.'] ';
				} else {
					$sString .= ' <a href="?'.$this->sGetParameter.'='.$iNum.'">'.$iNum.'</a> ';
				}
			}
			
			$sString .= NavigationOutput::getSpaceAfter();
			
			if(is_bool(NavigationOutput::getNext()))
				$sString .= $aWords['next'];
			else
				$sString .= ' | <a href="?'.$this->sGetParameter.'='.$aPags['next'].'">'.$aWords['next'].'</a>';
			
			if(is_bool(NavigationOutput::getLast()))
				$sString .= $aWords['last'];
			else
				$sString .= ' | <a href="?'.$this->sGetParameter.'='.$aPags['last'].'">'.$aWords['last'].'</a>';
		}
		
		return $sString;
	}
}

class NavigationDatabase extends Navigation {
	protected $oParent;
	
	public function __construct($oNavigation) {
		$this->oParent = $oNavigation;
	}
	
	// only use setQuery() and setQueryCountField()...
	public function setQuery($sQuery) {
		$this->oParent->sCountQuery = trim($sQuery);
	}
	
	// set fieldname which contains the query count result, standard value: aantal.
	public function setQueryCountField($sField) {
		$this->oParent->sQueryCountField = trim($sField);	
	}
	
	// ...or setQueryTable() and setQueryWhereStatement()
	public function setQueryTable($sTable) {
		$this->oParent->sTable = trim($sTable);
	}
	
	// set where statement for the query to be created with createQuery. If there's anything elses like JOINs used in the query, please use setQuery instead of these, cause setQuery is much more flexible to use with that kinds of queries.
	public function setQueryWhereStatement($sWhere) {
		$this->oParent->sWhereStatement = trim($sWhere);	
	}
	
	// only execute when setQuery() isn't used.
	protected function createQuery() {
		$this->oParent->sCountQuery = "SELECT COUNT(*) AS ".$this->oParent->sQueryCountField." FROM ".$this->oParent->sTable;
		
		if(!empty($this->oParent->sWhereStatement)) {
			$this->oParent->sCountQuery .= " WHERE ".$this->oParent->sWhereStatement;
		}
	}
	
	// calculate total pages amount.
	protected function calculateTotalPages() {
		$sResult = mysql_query($this->oParent->sCountQuery);
		if($sResult) {
			if(mysql_num_rows($sResult) > 0) {
				$sRij = mysql_fetch_assoc($sResult);
				
				$this->oParent->iTotal = ceil($sRij[$this->oParent->sQueryCountField]/$this->oParent->iShowRecords);
			} else {
				$this->oParent->iTotal = 0;			
			}
		} else {
			$this->oParent->iTotal = 0;
		}
	}
	
	// return the array, if everything completes, containing the results of the query of the showed page. 
	public function getQueryResult($sQuery) {
		$sResult = mysql_query($sQuery);
		if($sResult) {
			$aReturnArray = array();
			if(mysql_num_rows($sResult) > 0) {
				while($sRij = mysql_fetch_assoc($sResult)) {
					$aReturnArray[] = $sRij;				
				}
			}
		} else {
			throw new Exception(mysql_error().' in query: '.$sQuery);		
		}
		
		return $aReturnArray;
	}
	
	// when you create the query by your own, but not knowing how to use the LIMIT-statement, we make it for you.
	public function getLimit() {
		return ' LIMIT '.$this->oParent->iStart.','.$this->oParent->iShowRecords;
	}
}

class NavigationOutput extends Navigation {
	protected $oParent;
	
	public function __construct($oNavigation) {
		$this->oParent = $oNavigation;
	}
	
	// get the pagination array. this can also be used by the user of this class.
	public function getNavigation() {
		return $this->oParent->aPagination;	
	}
	
	public function getCurrent() {
		return str_replace($this->oParent->aToCurrentReplacements[1], $this->oParent->iCurrent, $this->oParent->aToCurrentReplacements[0]);
	}
	
	// get next page in the array.
	public function getNext() {
		if($this->oParent->aPagination['next'] === false) {
			return $this->oParent->aWords['next'];
		} else {
			return '<a href="?'.$this->oParent->sGetParameter.'='.$this->oParent->aPagination['next'].'">'.$this->oParent->aWords['next'].'</a>';		
		}
	}
	
	// get last page in the array.
	public function getLast() {
		if($this->oParent->aPagination['last'] === false) {
			return $this->oParent->aWords['last'];
		} else {
			return '<a href="?'.$this->oParent->sGetParameter.'='.$this->oParent->aPagination['last'].'">'.$this->oParent->aWords['last'].'</a>';		
		}
	}
	
	// get previous page in the array.
	public function getPrevious() {
		if($this->oParent->aPagination['prev'] === false) {
			return $this->oParent->aWords['prev'];
		} else {
			return '<a href="?'.$this->oParent->sGetParameter.'='.$this->oParent->aPagination['prev'].'">'.$this->oParent->aWords['prev'].'</a>';		
		}
	}
	
	// get first page in the array.
	public function getFirst() {
		if($this->oParent->aPagination['first'] === false) {
			return $this->oParent->aWords['first'];
		} else {
			return '<a href="?'.$this->oParent->sGetParameter.'='.$this->oParent->aPagination['first'].'">'.$this->oParent->aWords['first'].'</a>';		
		}
	}
	
	// get the pagination numbers in the array.
	public function getNumbers() {
		if(empty($this->oParent->aPagination['numbers'])) {
			return '';
		} else {
			$sString = '';
			foreach($this->oParent->aPagination['numbers'] as $sKey => $sVal) {
				if($this->oParent->iCurrent == $sVal)
					$sString .= $this->getCurrent().' ';
				else
					$sString .= '<a href="?'.$this->oParent->sGetParameter.'='.$sVal.'">'.$sVal.'</a> ';
			}
			return trim($sString);
		}	
	}
	
	// get the points before the numbers in the array.
	public function getSpaceBefore() {
		return $this->oParent->aPagination['space_before'];	
	}
	
	// get the points after the numbers in the array.
	public function getSpaceAfter() {
		return $this->oParent->aPagination['space_after'];	
	}
}

try {
	if(isset($_GET['pag'])) {
		$iPage = (int)$_GET['pag'];
	} else {
		$iPage = 1;
	}
	
	$oPagination = new Navigation($iPage, 5, 4, 'pag');
	$oDatabase = new NavigationDatabase($oPagination);
	$oOutput = new NavigationOutput($oPagination);
	
	$oDatabase->setQueryTable('alfabet');
	$oPagination->doExecute();
	
	$oPagination->setWord('first', 'eerste');
	$oPagination->setWord('previous', 'vorige');
	$oPagination->setWord('next', 'volgende');
	$oPagination->setWord('last', 'laatste');
	
	$oPagination->setCurrentStringRegex('[*c]', '*c');
	$oPagination->setToStringRegex('*f | *p | *sb *n *sa | *x | *l', 		
		array(
			'*f'=>$oOutput->getFirst(),
			'*p'=>$oOutput->getPrevious(),
			'*sb'=>$oOutput->getSpaceBefore(),
			'*n'=>$oOutput->getNumbers(),
			'*sa'=>$oOutput->getSpaceAfter(),
			'*x'=>$oOutput->getNext(),
			'*l'=>$oOutput->getLast()
		)
	);
	
	$sQuery = "SELECT * FROM alfabet".$oDatabase->getLimit();
	$sArray = $oDatabase->getQueryResult($sQuery);
	
	if(is_array($sArray)) {
		if(!empty($sArray)) {
			foreach($sArray as $iKey => $aValue) {
				echo $aValue['id'].'. '.$aValue['letter'].'<br />';
			}
			
			echo '<div>'.$oPagination.'</div>';
		} else {
			echo 'Geen records gevonden.';	
		}
	}
} catch(Exception $e) {
	echo $e->getMessage() . $e->getLine();
}
?>

Reacties

0
Nog geen reacties.