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

Typesense Bundle Laravel Package

biblioverse/typesense-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to your composer.json:

    composer require biblioverse/typesense-bundle
    

    Register in config/bundles.php:

    return [
        // ...
        Biblioverse\TypesenseBundle\TypesenseBundle::class => ['all' => true],
    ];
    
  2. Configure Typesense Publish the default config:

    php bin/console typesense:install
    

    Update config/packages/typesense.yaml with your Typesense server details:

    typesense:
        client:
            host: 'http://localhost:8108'
            api_key: 'your-api-key'
            connection_timeout_seconds: 2
    
  3. First Use Case: Searching Inject the TypesenseClient and perform a search:

    use Biblioverse\TypesenseBundle\Client\TypesenseClientInterface;
    
    class MyController
    {
        public function __construct(private TypesenseClientInterface $typesense)
        {
        }
    
        public function search(Request $request)
        {
            $results = $this->typesense->search('books', $request->query->get('q'));
            return $this->json($results);
        }
    }
    

Key Entry Points

  • Client Interface: TypesenseClientInterface (PSR-15 compliant).
  • Commands: php bin/console typesense:install (config), typesense:schema:dump (schema export).
  • Doctrine Integration: Optional TypesenseEntityListener for auto-indexing entities (requires config).

Implementation Patterns

Core Workflows

  1. Schema Management Define schemas in YAML (e.g., config/typesense/schemas/books.yaml):

    name: books
    fields:
        title: {type: string}
        author: {type: string, optional: true}
    

    Load dynamically via:

    $this->typesense->loadSchema('books');
    
  2. CRUD Operations Use fluent methods for collections:

    // Create
    $this->typesense->create('books', ['title' => 'Laravel Up & Running']);
    
    // Update
    $this->typesense->update('books', 123, ['author' => 'Matt Stauffer']);
    
    // Delete
    $this->typesense->delete('books', 123);
    
  3. Search with Filters Combine queries and filters:

    $results = $this->typesense->search('books', 'laravel', [
        'filter_by' => 'author:Matt Stauffer',
        'per_page' => 10,
    ]);
    
  4. Bulk Operations Use TypesenseBulkClient for batch imports:

    $this->typesense->bulk()->add('books', [
        ['id' => 1, 'title' => 'Book 1'],
        ['id' => 2, 'title' => 'Book 2'],
    ])->commit();
    

Integration Tips

  • Symfony Forms: Bind Typesense results to form choices:
    $choices = $this->typesense->search('authors', $request->query->get('q'));
    $form->add('author', ChoiceType::class, ['choices' => array_column($choices, 'name', 'id')]);
    
  • Messenger Integration: Dispatch search queries as messages for async processing.
  • Cache Results: Decorate TypesenseClient to cache responses (e.g., with Symfony Cache component).

Gotchas and Tips

Pitfalls

  1. Schema Mismatches

    • Issue: Updating a schema without reindexing causes errors.
    • Fix: Use typesense:schema:rebuild to drop and recreate collections:
      php bin/console typesense:schema:rebuild books
      
    • Tip: Version schemas in config (e.g., books_v1.yaml) and track changes.
  2. Rate Limiting

    • Issue: Default connection_timeout_seconds (2s) may trigger retries unnecessarily.
    • Fix: Adjust in config or implement exponential backoff in a custom client decorator.
  3. Doctrine Auto-Indexing

    • Issue: TypesenseEntityListener may not handle circular references or complex types.
    • Fix: Exclude problematic fields in @Typesense\Ignore or override the listener.
  4. API Key Exposure

    • Issue: Hardcoding API keys in typesense.yaml risks leaks.
    • Fix: Use Symfony’s %env% or parameter_bag:
      api_key: '%env(TYPESENSE_API_KEY)%'
      

Debugging

  • Enable Verbose Logging Add to config/packages/monolog.yaml:
    handlers:
        typesense:
            type: stream
            path: "%kernel.logs_dir%/%env(default::typesense).log%"
            level: debug
    
  • Check Raw Responses Decorate TypesenseClient to log raw API calls:
    $client->getHttpClient()->getEventDispatcher()->addListener(
        'request',
        function (RequestEvent $event) {
            error_log($event->getRequest()->getBody()->getContents());
        }
    );
    

Extension Points

  1. Custom Clients Implement TypesenseClientInterface for specialized behavior (e.g., retry logic):

    class RetryTypesenseClient implements TypesenseClientInterface
    {
        public function __construct(private TypesenseClientInterface $decorated) {}
    
        public function search(string $collection, string $query, array $options = []): array
        {
            return $this->decorated->search($collection, $query, $options);
        }
        // Add retry logic here
    }
    
  2. Schema Builders Extend SchemaBuilder to support dynamic fields:

    class DynamicSchemaBuilder extends SchemaBuilder
    {
        public function addDynamicField(string $name): self
        {
            $this->schema['fields'][$name] = ['type' => 'string', 'optional' => true];
            return $this;
        }
    }
    
  3. Event Listeners Subscribe to TypesenseEvents (e.g., SchemaLoadedEvent) for post-processing:

    $dispatcher->addListener(TypesenseEvents::SCHEMA_LOADED, function (SchemaLoadedEvent $event) {
        // Modify schema before indexing
    });
    

Pro Tips

  • Use Collections for Analytics Leverage Typesense’s collections API to group related schemas (e.g., books, reviews under library).
  • Leverage Multi-tenancy Prefix collections by tenant ID (e.g., tenant_123_books) and use filter_by for isolation.
  • Monitor with Health Checks Add a custom command to verify Typesense connectivity:
    php bin/console typesense:health
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle