You could do something like this. I would personally though factor each one out into separate methods. The problem there though is repetition. This is one of the problems you run into when using a DAO.
PHP Code:
listAnimals($limit=null,$offset=null) {
$sql = 'SELECT * FROM animals';
if(!is_null($limit) && !is_null($offset)) {
$stmt = $this->_dbh->prepare($sql.' LIMIT :limit,:offset');
$stmt->bindParam(':limit',$limit, PDO::PARAM_INT);
$stmt->bindParam(':offset',$offset, PDO::PARAM_INT);
} else if(!is_null($limit)) {
$stmt = $this->_dbh->prepare($sql.' LIMIT :limit');
$stmt->bindParam(':limit',$limit, PDO::PARAM_INT);
} else {
$stmt = $this->_dbh->prepare($sql);
}
}
Where as, if you were using a generic Mapper or ActiveRecord:
PHP Code:
Animal::find();
Animal::find(array('limit'=>10);
Animal::find(array('limit'=>10,'offset'=>10));
PHP Code:
$animal->get();
$animal->get(array('limit'=>10));
$animal->get(array('limit'=>10,'offset'=>10));
Eliminating all forms of repetition regardless of whether there is a offset, limit, etc.
This is how I handle pagination and the associated query.
PHP Code:
/*
* counts total animals returns integer
*/
$total = Animal::count();
/*
* Create pagination instance that handle calculations based on number per page, total and current page. If the current page
* exceeds the number of pages the current page becomes the last page.
*/
$page = 1;
$perPage = 20;
$pagination = new Pagination($perPage,$total,$page);
/*
* embed the offset and limit in query
*/
$animals = Animal::find(array('limit'=>$pagination->getCount(),'offset'=>$pagination->getOffset()));
The pagination instance is then passed to the view and two methods can be called to build the control interface. This gets a bit complex, but the substring {page} will be replaced by the page number of the associated control. So the variable $route is the base url. The makeMenu and makeDropDown methods use that url and replace {page} with actual page for the control… if that makes sense.
The call to makeUrl() of the $path variable replaces the current page variable named path with {page}. So if the current page url was: /animals/1 and the second item was the page the url returned would be: /animals/{page}.
PHP Code:
$route = $path->makeUrl(array('page'=>'{page}'));
echo $pagination->makeMenu($route);
echo $pagination->makeDropDown($route,'pagination-drop-down');
Bookmarks