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

Apisearch Bundle Laravel Package

apisearch-io/apisearch-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require apisearch-io/apisearch-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Apisearch\Bundle\ApisearchBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference apisearch
    

    Configure config/packages/apisearch.yaml:

    apisearch:
        api_key: "%env(APISEARCH_API_KEY)%"
        endpoint: "%env(APISEARCH_ENDPOINT)%"
        project_id: "%env(APISEARCH_PROJECT_ID)%"
    
  3. First Use Case Inject the client into a service/controller:

    use Apisearch\Bundle\ApisearchBundle\Client\ApisearchClient;
    
    class SearchController extends AbstractController
    {
        public function __construct(private ApisearchClient $client) {}
    
        public function search(Request $request)
        {
            $query = $request->query->get('q');
            $results = $this->client->search($query);
            return $this->json($results);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Search Integration

    • Use the ApisearchClient to execute queries:
      $results = $this->client->search('query', [
          'page' => 1,
          'size' => 10,
          'filters' => ['category' => 'electronics']
      ]);
      
    • Handle pagination with nextPage() and prevPage() methods.
  2. Document Management

    • Index documents:
      $this->client->index('products', [
          'id' => '123',
          'name' => 'Laptop',
          'price' => 999.99
      ]);
      
    • Bulk operations:
      $this->client->bulkIndex('products', [
          ['id' => '1', 'name' => 'Item 1'],
          ['id' => '2', 'name' => 'Item 2']
      ]);
      
  3. Event-Driven Updates

    • Listen to ApisearchEvents (e.g., Indexed, Deleted) via Symfony’s event dispatcher:
      $dispatcher->addListener(ApisearchEvents::INDEXED, function (IndexedEvent $event) {
          // Log or process indexed documents
      });
      

Integration Tips

  • Symfony Forms Use the bundle’s ApisearchType for search form fields:

    use Apisearch\Bundle\ApisearchBundle\Form\Type\ApisearchType;
    
    $builder->add('search', ApisearchType::class, [
        'label' => 'Search',
        'project_id' => 'your_project_id',
    ]);
    
  • Command-Line Tools Leverage the ApisearchCommand for CLI operations:

    php bin/console apisearch:index products data/products.json
    
  • Caching Cache search results using Symfony’s cache system:

    $cacheKey = 'search_results_' . md5($query);
    $results = $this->cache->get($cacheKey, function () use ($query) {
        return $this->client->search($query);
    });
    

Gotchas and Tips

Common Pitfalls

  1. API Key Management

    • Ensure APISEARCH_API_KEY is set in .env and not hardcoded.
    • Use environment variables for endpoint and project_id to avoid exposing secrets.
  2. Rate Limiting

    • The bundle respects Apisearch’s rate limits. Monitor responses for 429 errors and implement retries:
      try {
          $results = $this->client->search($query);
      } catch (RateLimitExceededException $e) {
          sleep(1); // Retry after delay
          $results = $this->client->search($query);
      }
      
  3. BC Breaks

    • The bundle has undergone changes (e.g., PHP 8 support in 0.1.17, BC breaks in 0.2.0). Check the changelog for version-specific behaviors.
  4. UUID Handling

    • The bundle uses ramsey/uuid for document IDs. Ensure your documents include a valid UUID or handle conversion:
      $document['id'] = (new Uuid())->toString();
      

Debugging Tips

  • Enable Debug Mode Set debug: true in apisearch.yaml to log API requests/responses:

    apisearch:
        debug: true
    
  • Symfony Profiler Use the ApisearchStopwatch to inspect search queries in the Symfony Profiler:

    $this->client->search($query, ['stopwatch' => true]);
    
  • Error Handling Catch specific exceptions:

    try {
        $this->client->delete('products', '123');
    } catch (DocumentNotFoundException $e) {
        // Handle missing document
    } catch (ApisearchException $e) {
        // Generic error handling
    }
    

Extension Points

  1. Custom Clients Extend ApisearchClient to add project-specific methods:

    class CustomApisearchClient extends ApisearchClient
    {
        public function searchByCategory(string $category, int $limit = 10)
        {
            return $this->search('', [
                'filters' => ['category' => $category],
                'size' => $limit
            ]);
        }
    }
    
  2. Event Subscribers Create subscribers for ApisearchEvents to trigger actions (e.g., analytics, notifications):

    class SearchAnalyticsSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                ApisearchEvents::SEARCH => 'onSearch',
            ];
        }
    
        public function onSearch(SearchEvent $event)
        {
            // Log search queries
        }
    }
    
  3. Middleware Add custom middleware to the HTTP client for logging, auth, or request transformation:

    $client = new ApisearchClient($config);
    $client->getHttpClient()->setMiddleware([
        new CustomMiddleware(),
    ]);
    
  4. Testing Use the ApisearchTestClient for unit tests:

    $testClient = new ApisearchTestClient($this->createMock(ApisearchClient::class));
    $results = $testClient->search('test');
    $this->assertCount(2, $results);
    

Configuration Quirks

  • Drift Integration The bundle relies on drift/http-kernel for HTTP handling. Ensure compatibility if using Symfony 5+:

    # config/packages/drift.yaml
    drift:
        http_kernel: true
    
  • Project ID Validation The project_id must match the Apisearch project ID format (e.g., UUID). Validate early:

    if (!Uuid::isValid($projectId)) {
        throw new \InvalidArgumentException('Invalid project ID format');
    }
    
  • Deprecated Methods Some methods (e.g., ApisearchClient::query()) may be deprecated. Prefer search() for consistency.

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky