Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/gargron/paginator

Minimal PHP paginator class. Generates pagination navigation based on total items number and offset.
https://github.com/gargron/paginator

Last synced: 2 months ago
JSON representation

Minimal PHP paginator class. Generates pagination navigation based on total items number and offset.

Awesome Lists containing this project

README

        

# Paginator

Very small PHP class to generate pagination links.

## Usage

In your controller/route:

'to_persist_on_paginator_links');

$paginator = new Gargron\Paginator('/example/url', $offset, $per_page, $total_items, $query_items);
?>

In your view or wherever you want the links rendered:

links(); ?>

## Alternative usage

If you don't want to count the total number of results (as it may be an expensive and unneccessary query),
the paginator can render simple next/previous links instead, but guessing if the respective link is needed.

'to_persist_on_paginator_links');

$paginator = new Gargron\Paginator('/example/url', $offset, $per_page, null, $query_items);
$paginator->currentFetched = $fetched;

In your view or where you want the links rendered:

links(); ?>

The logic behind this is very simple. If the number of actually fetched items is greater than the number
of items we want to display per page, it means there *is* a next page available. As for the previous link,
if the offset is greater than 0, there must be a previous page.

## Localization (and dependency)

The class uses the function `__()` when rendering the links. If you are not using a framework
that already defines that function, you can define it as follows:

function __($key)
{
$translations = array(
'pagination.first' => 'First',
'pagination.previous' => 'Previous',
'pagination.next' => 'Next',
'pagination.last' => 'Last',
);

return array_key_exists($key, $translations) ? $translations[$key] : $key;
}

I understand that adding a makedo function like that may not seem optimal, but if you are ever going
to localize your application, you'll be happy your Paginator class doesn't need any monkeypatching!

## Example of generated mark-up

### License

Paginator is released under the [MIT license](http://www.opensource.org/licenses/MIT).