Regarding class configuration - if there aren't many properties, there's no problem with using class variables. If there are many, one alternative is to use a configuration array. The definition of "many" is very fluid, and differs plenty from developer to developer.
For example, configuration array:
Code: Select all
<?php
class Pagination {
protected $config;
public function setConfig($config) {
$this -> config = $config;
}
public function output() {
$page_table = $this -> config['page_table'];
$per_page = $this -> config['per_page'];
...
}
}
$config = array(
'page_table' => $page_table,
'per_page' => 10
);
$pagination = new Pagination();
$pagination -> setConfig($config);
For configuration it's common to use a
constructor (a function which runs when the object is created, see the link):
Code: Select all
<?php
class Pagination {
protected $config;
public function __construct($config = null) {
$this -> setConfig($config);
}
public function setConfig($config) {...}
public function output() {...}
}
$config = array(
'page_table' => $page_table,
'per_page' => 10
);
$pagination = new Pagination($config);
this setConfig() method should probably check that all the necessary configuration options are present and return an error if not.
A couple more points -
1. To count rows in mysql, it's best to run a COUNT query:
Code: Select all
$result = mysql_query("SELECT COUNT(*) AS count FROM " . $page_table);
$row = mysql_fetch_array($result);
$num = current($row);
Your original query basically scans the entire table, which could be slow depending on the size of the table.
2. It's good practice not to echo/print inside class methods, unless there is no chance for reuse (final output). Since you are calling the Pagination class from the global scope, the echo should be there. Concatenate your output and return it from the function. This way you could perform more manipulations on the string if you need to.
Code: Select all
<?php
class Pagination {
public function __construct($config = null) {...}
public function setConfig($config) {...}
public function output(){
$i = 1;
$output = '<div class="pagination">'
. '<a href=""><</a>';
while($i <= $pages):
$output .= '<a href="'.$php_self.'?page='.$i.'">'.$i.'</a>';
$i++;
endwhile;
$output .= '<a href="">></a>'
. '</div>';
return $output;
}
}
$config = array(
'page_table' => $page_table,
'per_page' => 10
);
$pagination = new Pagination($config);
echo $pagination -> output(); // Output is echoed here