In PHP, how do I paginate objects with SPL?

This example demonstrates how to paginate a collection of objects using PHP and SPL.

Keywords: pagination, SPL, PHP, objects, example
Description: This code snippet shows how to create a simple pagination system for an array of objects in PHP using the Standard PHP Library.
<?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(); ?>

Keywords: pagination SPL PHP objects example