Paginator
in package
Pagination metadata container with navigation URL generation and integration support
Comprehensive pagination solution providing metadata storage, navigation logic, and URL generation for paginated data sets. Designed as immutable data container with helper methods for seamless integration with Model, QueryBuilder, and web application pagination interfaces.
Pagination Architecture
- Immutable Data Container: Stores pagination metadata without modification after construction
- URL Generation: Creates navigation URLs with query parameter preservation
- Framework Integration: Seamless integration with Model and QueryBuilder pagination methods
- Boundary Handling: Proper null returns for invalid navigation scenarios
- Flexible Construction: Support for automatic or manual page count calculation
Data Storage Model
The Paginator maintains complete pagination state through public properties:
- Current page data subset (arrays or model instances)
- Total item count across all pages
- Items per page configuration
- Current page number (1-based indexing)
- Total page count (calculated or provided)
Integration Patterns
Paginator instances are typically created by:
- Model::paginate(): Raw data pagination from database queries
- Model::paginateAsModels(): Model instance pagination with object conversion
- QueryBuilder::paginate(): Direct query builder pagination support
- Manual Construction: Custom pagination scenarios with external data sources
Navigation Logic
Navigation methods provide safe boundary checking:
- Next/Previous URL generation with automatic boundary detection
- Query parameter preservation for search filters and sorting
- Null returns for invalid navigation attempts (first/last page boundaries)
- Consistent URL format with 'page' and 'limit' parameters
Page Calculation Algorithm
Total pages calculated using: ceil(total_items / items_per_page)
- Handles edge cases: empty results, single page, fractional pages
- Supports override for custom page calculation scenarios
- 1-based page numbering throughout the system
Tags
Table of Contents
Properties
- $currentPage : int
- Current page number using 1-based indexing
- $data : array<string|int, mixed>
- Current page data subset as array of records or model instances
- $pages : int
- Total number of pages in complete pagination sequence
- $perPage : int
- Maximum number of items displayed per page
- $total : int
- Total number of items across all pages in complete dataset
Methods
- __construct() : mixed
- Initialize pagination container with data and metadata calculation
- hasMore() : bool
- Check if additional pages exist beyond the current page
- nextUrl() : string|null
- Generate URL for next page with query parameter preservation
- prevUrl() : string|null
- Generate URL for previous page with query parameter preservation
Properties
$currentPage
Current page number using 1-based indexing
public
int
$currentPage
Represents the currently displayed page within the pagination sequence. Uses 1-based numbering for human-friendly display and URL parameters. Essential for navigation boundary checking and URL generation logic.
Index Convention
- First Page: 1 (not 0)
- Page Numbers: Sequential integers starting from 1
- URL Parameters: Matches 'page' parameter in generated URLs
Boundary Conditions
- Minimum: 1 (first page)
- Maximum: $pages (last available page)
- Navigation: Used to determine next/previous availability
Current page number (1-based indexing)
Tags
$data
Current page data subset as array of records or model instances
public
array<string|int, mixed>
$data
Contains the actual data items for the current page, either as associative arrays (from raw database results) or as Model instances (from paginateAsModels). The exact data structure depends on the originating pagination method.
Data Types
- Raw Arrays: From Model::paginate() and QueryBuilder::paginate()
- Model Instances: From Model::paginateAsModels()
- Mixed Data: From manual Paginator construction
Empty Page Handling
Empty array when no results exist for current page or when total results are zero. Safe for foreach iteration and array operations.
Current page data items (arrays or objects)
Tags
$pages
Total number of pages in complete pagination sequence
public
int
$pages
Calculated total of pages needed to display all items based on items per page configuration. Used for navigation boundary checking and pagination interface rendering. Can be manually overridden during construction for custom scenarios.
Calculation Method
Default: ceil(total / perPage)
for automatic calculation
- Empty Results: 0 pages when total is 0
- Partial Pages: Rounds up fractional pages (e.g., 2.3 pages → 3 pages)
- Single Page: 1 when total ≤ perPage
Override Support
Manual override available in constructor for external pagination systems that provide pre-calculated page counts (APIs, cached results).
Navigation Logic
Used by hasMore() and URL generation methods to prevent invalid navigation:
- Next page available when currentPage < pages
- Previous page available when currentPage > 1
Total pages in pagination sequence (0 for empty results)
Tags
$perPage
Maximum number of items displayed per page
public
int
$perPage
Defines page size for pagination calculations and navigation logic. Determines how many items are included in each page and affects total page count calculation. Consistent across all pages in pagination sequence.
Usage in Calculations
- Page Count:
ceil(total / perPage)
for total pages - Offset Calculation:
(currentPage - 1) * perPage
for database queries - Range Display: "Items 21-40" calculations
URL Generation
Included as 'limit' parameter in generated navigation URLs to maintain consistent page sizing across navigation actions.
Items per page (positive integer)
Tags
$total
Total number of items across all pages in complete dataset
public
int
$total
Represents full result count before pagination limits are applied. Used for calculating total page count and providing result statistics to users. Essential for navigation logic and pagination interface rendering.
Calculation Source
- Database Count: From COUNT(*) queries in Model/QueryBuilder pagination
- External APIs: From API response total count fields
- Manual Construction: Provided explicitly during instantiation
Usage in Templates
Display total results: "Showing 21-40 of 157 results" Calculate result ranges and pagination statistics
Total items across all pages (0 for empty results)
Tags
Methods
__construct()
Initialize pagination container with data and metadata calculation
public
__construct(array<string|int, mixed> $data, int $total, int $perPage, int $currentPage[, int|null $pages = null ]) : mixed
Creates immutable pagination instance with provided data and metadata. Performs automatic page count calculation unless explicitly overridden. Establishes complete pagination state for navigation and display operations.
Automatic Calculations
- Page Count:
ceil(total / perPage)
when pages parameter is null - Boundary Validation: Ensures sensible defaults for edge cases
- Immutable State: All properties set during construction, no later modification
Constructor Flexibility
- Manual Page Count: Override automatic calculation for external systems
- Mixed Data Types: Supports arrays, objects, or mixed data structures
- Zero Results: Handles empty datasets gracefully
Integration Patterns
Typically called by framework pagination methods rather than directly:
- Model::paginate() provides raw array data
- Model::paginateAsModels() provides model instance data
- Custom construction for external APIs or cached results
Parameters
- $data : array<string|int, mixed>
-
Current page data subset (arrays or objects)
- $total : int
-
Total number of items across all pages
- $perPage : int
-
Maximum items per page for pagination calculation
- $currentPage : int
-
Current page number (1-based indexing)
- $pages : int|null = null
-
Optional override for total pages (calculated if null)
Tags
hasMore()
Check if additional pages exist beyond the current page
public
hasMore() : bool
Boolean convenience method for determining next page availability without generating URLs. Useful for conditional logic, navigation enabling/disabling, and pagination interface state management.
Comparison Logic
Returns true when currentPage < pages, indicating:
- More pages available for navigation
- Next page button should be enabled
- Additional data exists beyond current page
Use Cases
- Conditional Navigation: Show/hide next page controls
- JavaScript Integration: Enable/disable navigation buttons
- Template Logic: Conditional rendering without URL generation overhead
- API Responses: Include hasMore flag in pagination metadata
Performance Advantage
Lightweight boolean check without URL generation overhead when only availability status is needed, not actual navigation URLs.
Tags
Return values
bool —True if more pages exist after current page, false otherwise
nextUrl()
Generate URL for next page with query parameter preservation
public
nextUrl(string $baseUrl[, array<string, mixed> $params = [] ]) : string|null
Creates complete URL for next page navigation including preserved query parameters and pagination metadata. Returns null when already on last page to prevent invalid navigation attempts. Merges provided parameters with pagination parameters.
URL Construction
- Base URL: Provided base URL without modification
- Query Parameters: Merged additional params + 'page' + 'limit'
- Parameter Priority: Additional params override pagination params if conflicting
- URL Format: Standard HTTP query string format via http_build_query()
Boundary Checking
Performs automatic boundary validation:
- Returns null when currentPage >= pages (already on last page)
- Next page calculated as currentPage + 1
- Safe navigation without manual boundary checking
Parameter Preservation
Maintains search, filter, and sorting parameters across navigation:
- Existing query parameters preserved in URL
- Search terms, filters, and sort options maintained
- Enables consistent user experience during navigation
Parameters
- $baseUrl : string
-
Base URL for pagination (without query parameters)
- $params : array<string, mixed> = []
-
Additional query parameters to preserve
Tags
Return values
string|null —Complete URL for next page or null if on last page
prevUrl()
Generate URL for previous page with query parameter preservation
public
prevUrl(string $baseUrl[, array<string, mixed> $params = [] ]) : string|null
Creates complete URL for previous page navigation with preserved query parameters and pagination metadata. Returns null when already on first page to prevent invalid navigation attempts. Maintains consistent URL format with nextUrl().
URL Construction Process
- Base URL: Uses provided base URL as foundation
- Query Merging: Combines additional params with pagination parameters
- Page Calculation: Previous page = currentPage - 1
- URL Encoding: Proper query string encoding via http_build_query()
First Page Boundary
Automatic boundary checking prevents invalid navigation:
- Returns null when currentPage <= 1 (already on first page)
- No need for manual boundary validation in templates
- Consistent behavior with nextUrl() boundary handling
Search and Filter Preservation
Maintains user's current search context during navigation:
- Search queries preserved across page changes
- Filter selections maintained
- Sort preferences carried forward
Parameters
- $baseUrl : string
-
Base URL for pagination (without query parameters)
- $params : array<string, mixed> = []
-
Additional query parameters to preserve
Tags
Return values
string|null —Complete URL for previous page or null if on first page