我不得不做一個分頁腳本,我必須特別注意性能,安全性和算法。我想出了以下代碼:分頁腳本的效率和性能
<?php
class Paginador{
public $current_page; // current page
public $total_pages; // total
public $boundaries = 1; // pages to link in the beggining and in the end
public $around = 1; // pages to link before and after the current
public $pageArray = array(); // array com toda a informação a paginar
function __construct($current_page, $total_pages, $boundaries = 1, $around = 1){
$this->current_page = $current_page;
$this->total_pages = $total_pages;
$this->boundaries = $boundaries;
$this->around = $around;
}
function __destruct(){
$this->current_page = 0;
$this->total_pages = 0;
$this->boundaries = 0;
$this->around = 0;
}
function setCurrentPage($newValue){
$this->current_page = $newValue;
return $this;
}
function setTotalPages($newValue){
$this->total_pages = $newValue;
return $this;
}
function setBoundaries($newValue){
$this->boundaries = $newValue;
return $this;
}
function setAround($newValue){
$this->around = $newValue;
return $this;
}
function generateLeftBoundaries(){
if ($this->boundaries + $this->around > $this->current_page) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray(1 , $this->current_page));
} else {
if ($this->boundaries > 0) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray(1, 1 + ($this->boundaries - 1)));
}
if ($this->around > 0) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray($this->current_page - $this->around, $this->current_page));
}
}
}
function generateRightBoundaries() {
if ($this->boundaries + $this->around + $this->current_page > $this->total_pages) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray($this->current_page, $this->total_pages));
} else {
if ($this->around > 0) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray($this->current_page, $this->current_page + $this->around));
}
if ($this->boundaries > 0) {
$this->pageArray = array_merge($this->pageArray, $this->populateArray($this->total_pages - ($this->boundaries - 1), $this->total_pages));
}
}
}
function populateArray($start, $end) {
$output = array();
for ($i = $start; $i <= $end; $i++) {
$output[] = $i;
}
return $output;
}
function paginate(){
//create the structure
$this->pageArray = array();
$this->generateLeftBoundaries();
$this->pageArray[] = $this->current_page;
$this->generateRightBoundaries();
$this->pageArray[] = $this->total_pages;
$this->pageArray = array_values(array_unique($this->pageArray));
//now print the pagination array
$pages = $this->pageArray;
$items = count($pages);
for ($i = 0; $i < $items; $i++) {
$current_page = $pages[ $i ];
echo $current_page . ' ';
if (($i + 1) < $items
&& $pages[ $i + 1 ] != ($current_page + 1)) {
echo '...';
}
}
}
}
?>
此代碼當前按預期工作,我的問題是關於性能,易讀性和安全性。我如何改進此代碼以提高效率並更容易理解。如果你能說明它爲什麼會很好的原因。 Thx提前!
這個問題似乎是脫離主題 - 它會更適當地問在http://codereview.stackexchange.com –