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

Recommendations Bundle Laravel Package

andres-montanez/recommendations-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require andres-montanez/recommendations-bundle
    

    Add to AppKernel.php:

    new AndresMontanez\RecommendationsBundle\RecommendationsBundle(),
    
  2. Configure MongoDB Ensure your config.yml includes MongoDB connection details:

    andres_montanez_recommendations:
        mongo_db: your_database_name
        mongo_host: localhost
        mongo_port: 27017
    
  3. First Use Case: Register Items

    $recommendationService = $this->get('andres_montanez_recommendations.recommendation');
    $recommendationService->registerItem('movie', 'batman', ['action', 'drama'], 'default_namespace');
    
  4. Register User Actions

    $recommendationService->addAction('user_123', 'rated', 'movie', 'batman', 5, 'default_namespace');
    
  5. Trigger Similarity Update (via Cron)

    php app/console andres-montanez:recommendations:update-similarities
    

Implementation Patterns

Core Workflows

  1. Item Registration

    • Use registerItem() for products, movies, or any entity.
    • Pattern: Batch-register items during import (e.g., product seeding):
      foreach ($products as $product) {
          $recommendationService->registerItem('product', $product->id, $product->tags, 'ecommerce_namespace');
      }
      
  2. User Interaction Tracking

    • Log actions like viewed, purchased, or rated:
      $recommendationService->addAction($userId, 'purchased', 'product', $productId, 1, 'ecommerce_namespace');
      
    • Tip: Use events (e.g., ProductViewedEvent) to auto-log interactions.
  3. Fetching Recommendations

    • Basic recommendations:
      $recommendations = $recommendationService->getRecommendations('user_123', 'default_namespace');
      
    • Filter by type/tag:
      $recommendations = $recommendationService->getRecommendations(
          'user_123',
          'default_namespace',
          ['type' => 'movie', 'tags' => ['action']]
      );
      
      
  4. Cron Job Integration

    • Schedule update-similarities command weekly:
      0 3 * * 1 php /path/to/console andres-montanez:recommendations:update-similarities
      

Advanced Patterns

  1. Namespace Isolation

    • Use namespaces for multi-site setups (e.g., site_a, site_b):
      $recommendationService->registerItem('product', $id, [], 'site_a');
      
  2. Custom Value Scaling

    • Normalize values (e.g., 0-5 ratings → 0-1) for Pearson distance:
      $normalizedValue = $rawValue / 5.0;
      $recommendationService->addAction($userId, 'rated', 'movie', $id, $normalizedValue, 'namespace');
      
  3. Caching Layer

    • Cache recommendations for 24h using Symfony Cache:
      $cache = $this->get('cache.app');
      $key = "recs_{$userId}_{$namespace}";
      if (!$cache->has($key)) {
          $recommendations = $recommendationService->getRecommendations($userId, $namespace);
          $cache->set($key, $recommendations, 86400); // 24h
      }
      

Gotchas and Tips

Pitfalls

  1. Cold Start Performance

    • Issue: First update-similarities run is slow (O(n²) complexity).
    • Fix: Pre-populate with seed data or run during off-peak hours.
  2. Namespace Confusion

    • Issue: Mixing namespaces can skew recommendations.
    • Fix: Validate namespace consistency in addAction()/registerItem().
  3. Data Skew

    • Issue: Items with few interactions get poor recommendations.
    • Fix: Use a minimum interaction threshold (e.g., ignore items with <3 ratings).
  4. MongoDB Indexing

    • Issue: Slow queries if indexes are missing.
    • Fix: Ensure MongoDB indexes on user, item, and namespace fields.

Debugging Tips

  1. Log Similarities

    • Dump generated similarities for validation:
      $similarities = $this->get('andres_montanez_recommendations.similarities');
      file_put_contents('similarities.log', print_r($similarities->getAll(), true));
      
  2. Test with Small Datasets

    • Use the Movielens 100K dataset to verify behavior before scaling.
  3. Monitor Cron Jobs

    • Log execution time and errors:
      php app/console andres-montanez:recommendations:update-similarities --env=prod > /var/log/recs_update.log 2>&1
      

Extension Points

  1. Custom Similarity Metrics

    • Override PearsonDistance by extending the service:
      class CustomSimilarity extends \AndresMontanez\RecommendationsBundle\Similarity\PearsonDistance {
          protected function calculate($a, $b) { ... }
      }
      
    • Register as a service:
      services:
          custom_similarity:
              class: Your\Bundle\CustomSimilarity
              tags:
                  - { name: andres_montanez_recommendations.similarity }
      
  2. Post-Processing Recommendations

    • Filter or re-rank results in a wrapper:
      $rawRecs = $recommendationService->getRecommendations($userId, $namespace);
      $filteredRecs = array_filter($rawRecs, function($item) {
          return $item['score'] > 0.5; // Custom threshold
      });
      
  3. Hybrid Recommendations

    • Combine with popularity-based fallbacks:
      $recommendations = $recommendationService->getRecommendations($userId, $namespace);
      if (empty($recommendations)) {
          $recommendations = $this->getPopularItems($namespace);
      }
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui