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

efrag/paginator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require efrag/paginator-bundle "~2"
    

    Ensure your project uses Symfony 2.x/3.x (last release was 2019).

  2. Enable the Bundle: Add to app/AppKernel.php (Symfony 2/3) or config/bundles.php (Symfony 4+):

    new Efrag\Bundle\PaginatorBundle\EfragPaginatorBundle(),
    
  3. First Use Case: Inject the efrag_paginator.paginator service into a controller and generate pagination for a query result:

    use Efrag\Bundle\PaginatorBundle\Paginator\Paginator;
    
    class MyController extends Controller
    {
        public function indexAction(Paginator $paginator, $page = 1)
        {
            $results = $this->getDoctrine()->getRepository('App:MyEntity')->findAll();
            $pagination = $paginator->paginate($results, $page, 10, 'my_route_name');
    
            return $this->render('template.html.twig', [
                'pagination' => $pagination,
            ]);
        }
    }
    
  4. Twig Integration: Use the provided Twig extension to render pagination links:

    {{ pagination_links(pagination) }}
    

Implementation Patterns

Core Workflow

  1. Pagination Generation: Pass query results, current page, items per page, and route name to paginator->paginate():

    $pagination = $paginator->paginate($results, $currentPage, $itemsPerPage, 'route_name');
    
    • Route Parameters: Pass additional route parameters as an associative array:
      $pagination = $paginator->paginate($results, 1, 10, 'route_name', ['filter' => 'value']);
      
  2. Customizing Links: Override the Twig template (@EfragPaginator/pagination_links.html.twig) or extend the Paginator service to modify link generation logic.

  3. Dynamic Query Pagination: Use with Doctrine repositories or custom queries:

    $query = $em->createQuery('SELECT u FROM App:User u WHERE u.active = :active')
        ->setParameter('active', true);
    $pagination = $paginator->paginate($query->getResult(), $page, 10, 'user_list');
    
  4. API Responses: Return pagination metadata as JSON:

    return $this->json([
        'data' => $results,
        'pagination' => [
            'current_page' => $pagination->getCurrentPage(),
            'total_pages' => $pagination->getTotalPages(),
            'total_items' => $pagination->getTotalItems(),
        ],
    ]);
    

Integration Tips

  • Symfony Forms: Combine with Symfony\Component\Form\Extension\Core\Type\NumberType for page input:
    $builder->add('page', NumberType::class, [
        'attr' => ['min' => 1],
    ]);
    
  • AJAX: Use the paginate() method in AJAX calls to update content dynamically without full page reloads.
  • Caching: Cache pagination results if the underlying data rarely changes:
    $cacheKey = 'pagination_' . md5(serialize($results)) . '_' . $page;
    $pagination = $cache->get($cacheKey, function() use ($paginator, $results, $page) {
        return $paginator->paginate($results, $page, 10, 'route_name');
    });
    

Gotchas and Tips

Pitfalls

  1. Route Name Sensitivity:

    • The bundle requires a valid Symfony route name. If the route doesn’t exist, it throws a RuntimeException.
    • Fix: Verify route names with php bin/console debug:router or use absolute URLs as a fallback (extend the service).
  2. Query Result Handling:

    • The bundle expects an array or Traversable object. Doctrine QueryBuilder results must be fetched first (e.g., $query->getResult()).
    • Gotcha: Passing a QueryBuilder directly will fail with:
      Catchable Fatal Error: Object of class Doctrine\ORM\QueryBuilder could not be converted to string
      
    • Fix: Use $query->getResult() or $query->getScalarResult().
  3. Symfony 4+ Compatibility:

    • The bundle targets Symfony 2/3. For Symfony 4+, manually register the service in config/services.yaml:
      services:
          Efrag\Bundle\PaginatorBundle\Paginator\Paginator:
              arguments:
                  $router: '@router'
      
  4. Twig Extension Auto-Loading:

    • If pagination_links Twig function isn’t recognized, ensure the bundle’s Twig extension is loaded. For Symfony 4+, add this to config/packages/twig.yaml:
      twig:
          paths: ['%kernel.project_dir%/vendor/efrag/paginator-bundle/Resources/views']
      

Debugging

  1. Check Pagination Data: Dump the pagination object to verify structure:

    dump($pagination->getCurrentPage(), $pagination->getTotalPages(), $pagination->getItems());
    

    Expected output:

    array:3 [
      "current_page" => int 1
      "total_pages" => int 5
      "items" => array:10 [ ... ]
    ]
    
  2. Route Generation Issues:

    • If links are broken, check the route parameters:
      $router = $this->get('router');
      $url = $router->generate('route_name', ['page' => 2]);
      
    • Ensure the route accepts the page parameter (e.g., {page} in YAML routes).
  3. Performance:

    • Avoid paginating all results at once. Use Doctrine’s setFirstResult()/setMaxResults() for database-level pagination:
      $query->setFirstResult(($page - 1) * $itemsPerPage)
            ->setMaxResults($itemsPerPage);
      $pagination = $paginator->paginate($query->getResult(), $page, $itemsPerPage, 'route_name');
      

Extension Points

  1. Custom Pagination Class: Extend Efrag\Bundle\PaginatorBundle\Paginator\Paginator to add methods (e.g., getPreviousPageUrl()):

    class CustomPaginator extends Paginator
    {
        public function getPreviousPageUrl($route, $params = [])
        {
            $currentPage = $this->getCurrentPage();
            if ($currentPage > 1) {
                $params['page'] = $currentPage - 1;
                return $this->router->generate($route, $params);
            }
            return null;
        }
    }
    

    Register as a service in services.yaml:

    services:
        app.custom_paginator:
            class: App\Service\CustomPaginator
            arguments: ['@router']
            public: true
    
  2. Override Twig Templates: Copy vendor/efrag/paginator-bundle/Resources/views/pagination_links.html.twig to templates/bundles/EfragPaginator/pagination_links.html.twig and customize:

    {# Example: Add disabled state for current page #}
    <li class="active">{{ pagination.getCurrentPage() }}</li>
    
  3. Add CSS Classes: Pass options to paginate() to customize link attributes:

    $pagination = $paginator->paginate($results, 1, 10, 'route_name', [], [
        'link_attr' => ['class' => 'pagination-link'],
        'current_page_attr' => ['class' => 'active'],
    ]);
    

    Update the Twig template to use these attributes.

  4. Localization: Override translation keys in config/packages/efrag_paginator.yaml:

    efrag_paginator:
        labels:
            previous: '« Previous'
            next: 'Next »'
    
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