Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Paginator Bundle Laravel Package

arturdoruch/paginator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arturdoruch/paginator-bundle
    

    Register the bundle in AppKernel.php:

    new ArturDoruch\PaginatorBundle\ArturDoruchPaginatorBundle(),
    
  2. Basic Configuration (optional, defaults exist):

    # app/config/config.yml
    artur_doruch_paginator:
        limit: 10
        prev_page_label: '← Prev'
        next_page_label: 'Next →'
    
  3. First Use Case: In a controller, paginate a Doctrine ORM query:

    use ArturDoruch\PaginatorBundle\Paginator;
    
    public function indexAction($page = 1, Request $request)
    {
        $paginator = $this->get('arturdoruch_paginator');
        $qb = $this->getDoctrine()->getRepository('AppBundle:Post')->createQueryBuilder('p');
        $posts = $paginator->paginate($qb, $page, 10);
    
        return $this->render('post/index.html.twig', ['posts' => $posts]);
    }
    
  4. Twig Integration: Use the provided Twig functions in your template:

    {{ arturdoruch_pagination(posts.pagination) }}
    

Implementation Patterns

Common Workflows

1. Paginating Doctrine Queries

  • QueryBuilder:
    $qb = $this->getDoctrine()->getRepository('AppBundle:User')->createQueryBuilder('u')
        ->where('u.active = :active')
        ->setParameter('active', true);
    
    $users = $paginator->paginate($qb, $request->query->getInt('page', 1), 20);
    
  • Query Object:
    $query = $qb->getQuery();
    $users = $paginator->paginate($query, $page, 20);
    

2. Paginating Arrays

  • Useful for API responses or non-DB data:
    $data = ['item1', 'item2', ..., 'item100'];
    $paginatedData = $paginator->paginate($data, $page, 15);
    

3. Dynamic Limits

  • Override the default limit per request:
    $limit = $request->query->getInt('limit', 0); // 0 uses config default
    $paginatedData = $paginator->paginate($query, $page, $limit);
    

4. MongoDB Support

  • For Doctrine ODM or MongoDB cursors:
    $cursor = $this->getDoctrine()->getManager()->getConnection()->executeQuery('db.collection.find()');
    $paginatedCursor = $paginator->paginate($cursor, $page, 10);
    

Integration Tips

Routing and URL Generation

  • Pass the paginator object to Twig for URL generation:
    {% for page in arturdoruch_pagination_pages(posts.pagination) %}
        <a href="{{ path('post_index', {'page': page}) }}">{{ page }}</a>
    {% endfor %}
    

API Responses

  • Return paginated data as JSON:
    return new JsonResponse([
        'data' => $posts,
        'pagination' => [
            'total_items' => $posts->getTotalItemCount(),
            'current_page' => $posts->getCurrentPageNumber(),
            'last_page' => $posts->getLastPageNumber(),
        ]
    ]);
    

Custom Twig Extensions

  • Extend the bundle’s Twig functions for reusable components:
    {% macro paginationNav(pagination) %}
        <nav>
            {{ arturdoruch_pagination_prev(pagination) }}
            {{ arturdoruch_pagination_next(pagination) }}
        </nav>
    {% endmacro %}
    

Gotchas and Tips

Pitfalls

1. Page Number Validation

  • The bundle does not validate $page for negative values or non-integers. Sanitize in your controller:
    $page = max(1, $request->query->getInt('page', 1));
    

2. MongoDB Cursor Handling

  • MongoDB cursors must be iterable (e.g., not exhausted). Avoid calling toArray() before pagination.

3. Array Pagination Edge Cases

  • Empty arrays return null for pagination metadata. Handle gracefully:
    if (!$paginatedData) {
        return $this->render('empty.html.twig');
    }
    

4. Doctrine Query Modification

  • The bundle does not clone QueryBuilders/Queries. Avoid modifying them after pagination:
    // ❌ Bad: Modifies the original query
    $qb->andWhere('...');
    $paginator->paginate($qb, $page, 10);
    
    // ✅ Good: Clone if needed
    $clonedQb = clone $qb;
    $paginator->paginate($clonedQb, $page, 10);
    

Debugging Tips

1. Check Pagination Metadata

  • Inspect the returned object’s methods:
    $posts->getTotalItemCount();       // Total items
    $posts->getCurrentPageNumber();    // Current page
    $posts->getLastPageNumber();       // Last page
    $posts->getLimit();                // Items per page
    

2. Log Raw Queries

  • Enable Doctrine logging to verify SQL:
    # config.yml
    doctrine:
        dbal:
            logging: true
    

3. Test with -1 Limit

  • Use $limit = -1 to fetch all items (bypasses pagination) for debugging:
    $allItems = $paginator->paginate($query, 1, -1);
    

Extension Points

1. Custom Pagination Views

  • Override Twig templates in app/Resources/ArturDoruchPaginatorBundle/views/:
    app/
        Resources/
            ArturDoruchPaginatorBundle/
                views/
                    Pagination/
                        pagination.html.twig  # Override default
    

2. Add Custom Metadata

  • Extend the Pagination class (e.g., add hasNextPage()):
    // src/ArturDoruch/PaginatorBundle/Pagination.php
    public function hasNextPage()
    {
        return $this->getCurrentPageNumber() < $this->getLastPageNumber();
    }
    

3. Localization

  • Override labels in config:
    artur_doruch_paginator:
        prev_page_label: '« Anterior'
        next_page_label: 'Siguiente »'
    

4. Integration with Forms

  • Use the paginator with Symfony Forms for dynamic limits:
    $form = $this->createFormBuilder()
        ->add('limit', ChoiceType::class, [
            'choices' => [5, 10, 20, 50],
            'data' => $request->query->getInt('limit', 10),
        ])
        ->getForm();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware