Hello,
I've been working with the Pager library in CodeIgniter 4 and noticed that while it automatically handles the `page` parameter from the URL query string, it doesn't provide similar functionality for the number of items per page.
Current Behavior
Currently, the Pager class automatically reads the `page` parameter from the URL (e.g., `?page=5`), but the number of items per page (`perPage`) must be manually specified in the code:
PHP Code:
// Controller method
public function index()
{
$model = new MyModel();
$data = [
'items' => $model->paginate(20), // perPage hardcoded as 20
'pager' => $model->pager
];
return view('my_view', $data);
}
Proposed Enhancement
I'd like to propose adding support for a `perPage` parameter in the URL query string, similar to how the `page` parameter works. This would allow clients to specify how many items they want per page directly in the URL:
Code:
/users?page=5&perPage=50
The Pager library would automatically detect this parameter and use it instead of the default value or the one specified in the code.
Benefits
1.
Improved API Development: This would make the Pager more suitable for RESTful API development, where clients often need to control the pagination parameters.
2.
Consistent Interface: It would provide a consistent interface for both page number and page size parameters.
3.
Reduced Boilerplate: Developers wouldn't need to manually check for and apply the `perPage` parameter in every controller method.
4.
Better User Experience: Frontend applications could allow users to choose how many items they want to see per page.
Implementation Suggestion
The implementation could be similar to how the `page` parameter is handled in the `calculateCurrentPage()` method, with appropriate safety checks to ensure the value is within acceptable limits:
PHP Code:
// Inside the Pager class
protected function calculatePerPage(string $group)
{
$perPageSelector = 'perPage'; // or configurable
if (isset($_GET[$perPageSelector])) {
$perPage = (int) $_GET[$perPageSelector];
$minPerPage = 1;
$maxPerPage = $this->config->maxPerPage ?? 100;
$this->groups[$group]['perPage'] = max($minPerPage, min($perPage, $maxPerPage));
}
}
This would respect the existing API while adding the new functionality in a backward-compatible way.
Has anyone else found this limitation? Would this feature be valuable to the community?
Thank you for considering this enhancement!