This example demonstrates how to paginate a collection of objects using PHP and SPL.
<?php
class PaginatedCollection implements IteratorAggregate {
private $items;
private $perPage;
private $currentPage;
public function __construct(array $items, int $perPage) {
$this->items = $items;
$this->perPage = $perPage;
$this->currentPage = 1;
}
public function setCurrentPage(int $page) {
$this->currentPage = max(1, $page);
}
public function getItemsForCurrentPage() {
$offset = ($this->currentPage - 1) * $this->perPage;
return array_slice($this->items, $offset, $this->perPage);
}
public function getTotalPages() {
return ceil(count($this->items) / $this->perPage);
}
public function getIterator() {
return new ArrayIterator($this->getItemsForCurrentPage());
}
}
// Example usage
$items = range(1, 100); // An example array with 100 items
$collection = new PaginatedCollection($items, 10); // 10 items per page
// Set current page to 3
$collection->setCurrentPage(3);
echo "<ul>";
foreach ($collection as $item) {
echo "<li>Item " . $item . "</li>";
}
echo "</ul>";
echo "Page " . $collection->getCurrentPage() . " of " . $collection->getTotalPages();
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?