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

Elastica Query Sorter Bundle Laravel Package

alpixel/elastica-query-sorter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require alpixel/elastica-query-sorter-bundle
    

    Register the bundle in AppKernel.php:

    new Alpixel\Bundle\ElasticaQuerySorterBundle\AlpixelElasticaQuerySorterBundle(),
    
  2. Basic Configuration (config.yml):

    alpixel_elastica_query_sorter:
        views:
            clear_sort: "path/to/clear_sort_template.html.twig"
            sort_link: "path/to/sort_link_template.html.twig"
        item_per_page: 10  # Optional: Default items per page
    
  3. First Use Case:

    • Inject the service in a controller and pass an Elastica Query and Repository:
      $results = $this->get('alpixel.services.elastica_query_sorter')->sort($repository, $query);
      
    • Render results in Twig with elastica_sort() helper:
      <th>{{ elastica_sort('Name', 'name') }}</th>
      

Implementation Patterns

Workflows

  1. Controller Integration:

    • Use the service to sort and paginate results after building a custom Elastica query:
      $repository = $this->get('fos_elastica.manager')->getRepository('AppBundle:Product');
      $query = $repository->queryCustom($filters);
      $results = $this->get('alpixel.services.elastica_query_sorter')->sort($repository, $query);
      
    • Pass results to Twig for rendering.
  2. Twig Integration:

    • Sortable Headers: Use elastica_sort() in table headers to generate clickable sort links:
      <th>{{ elastica_sort('Price', 'price.value') }}</th>
      
    • Pagination: Use Pagerfanta’s templating (e.g., twitter_bootstrap3_translated):
      {{ pagerfanta(results, 'twitter_bootstrap3_translated') }}
      
  3. Dynamic Sorting:

    • The bundle automatically detects the current sort field/direction from the request (e.g., ?sort=price&direction=desc).
    • Override defaults via Twig:
      {{ elastica_sort('Name', 'name', {'default_direction': 'desc'}) }}
      
  4. Nested Fields:

    • Support nested Elastica mappings (e.g., product.serial_number) by passing dot-notation:
      {{ elastica_sort('Serial', 'product.serial_number') }}
      

Integration Tips

  • Elastica Mapping: Ensure your index mappings match the fields used in elastica_sort(). Example:
    # config/elastica.yml
    AppBundle\Document\Product:
        properties:
            price:
                type: float
            product:
                properties:
                    serial_number:
                        type: string
    
  • Form Integration: Combine with Symfony forms for filtered searches:
    $form = $this->createForm(MySearchForm::class);
    $form->handleRequest($request);
    $query = $repository->queryCustom($form->getData());
    
  • Custom Templates: Override default Twig templates (sort_link.html.twig, clear_sort.html.twig) in Resources/views/blocks/.

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • Last release in 2017 (Symfony 2.8). Test thoroughly with newer Symfony/Elastica versions.
    • Elastica 3.x Compatibility: May require patches for newer Elastica APIs (e.g., QueryBuilder changes).
  2. Twig Helper Dependencies:

    • elastica_sort() relies on the alpixel_elastica_query_sorter.views.sort_link template. If missing, sort links break.
    • Fix: Copy the default template from the bundle’s Resources/views/blocks/sort_link.html.twig to your project.
  3. Pagination Conflicts:

    • Pagerfanta must be configured separately (via white_october/pagerfanta-bundle). Ensure both bundles are properly initialized.
    • Debug: Check if results is a Pagerfanta\Pagerfanta instance. If not, the sorter may not be applied.
  4. Nested Field Sorting:

    • Dot-notation (e.g., product.serial_number) assumes the nested field exists in the mapping. Error: Silent failures if the path is invalid.
    • Debug: Verify mappings with:
      $client = $this->get('fos_elastica.client');
      $mapping = $client->getIndex('your_index')->getType('AppBundle:Product')->getMapping();
      
  5. Request Parameter Overrides:

    • Sorting is driven by ?sort=field&direction=asc/desc. Gotcha: Custom route parameters (e.g., @Route("/search/{sort}", ...)) may conflict.
    • Solution: Use Request::query to merge defaults:
      $sort = $request->query->get('sort', 'name');
      $direction = $request->query->get('direction', 'asc');
      

Debugging Tips

  1. Log Queries:

    • Enable Elastica debug logging to inspect generated queries:
      # config.yml
      fos_elastica:
          client: ~
          debug: true
      
    • Check logs for Elastica\Query objects.
  2. Template Debugging:

    • Override sort_link.html.twig to add debug info:
      {{ dump(app.request.query.all()) }}
      
  3. Service Availability:

    • Verify the service is registered:
      php bin/console debug:container alpixel.services.elastica_query_sorter
      
    • Fix: Clear cache if the service is missing:
      php bin/console cache:clear
      

Extension Points

  1. Custom Sort Logic:

    • Extend the sorter service by overriding Alpixel\Bundle\ElasticaQuerySorterBundle\Service\ElasticaQuerySorter:
      # config/services.yml
      services:
          app.elastica_query_sorter:
              class: AppBundle\Service\CustomElasticaQuerySorter
              parent: alpixel.services.elastica_query_sorter
              arguments: ['@fos_elastica.manager']
      
    • Implement custom sorting rules in sort() method.
  2. Dynamic Field Mapping:

    • Use a callback in elastica_sort() to dynamically resolve fields:
      {{ elastica_sort('Dynamic Field', app.callback('getSortField', ['field'])) }}
      
    • Register the callback in Twig:
      $twig->addFunction(new \Twig_SimpleFunction('callback', function ($name, $args) {
          return $this->get($name)->__invoke($args);
      }));
      
  3. Alternative Pagination:

    • Replace Pagerfanta with KnpPaginator by extending the service and modifying the sort() method to return a Knp\Component\Pager\Pagination\PaginationInterface.
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