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

Php Api Client Laravel Package

recombee/php-api-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require recombee/php-api-client
    

    Add credentials to .env:

    RECOMbee_DATABASE_ID=your-database-id
    RECOMbee_PRIVATE_TOKEN=your-private-token
    RECOMbee_REGION=us-west  # or eu-central, etc.
    
  2. Basic Setup: Register the client in config/services.php:

    'recombee' => [
        'database_id' => env('RECOMbee_DATABASE_ID'),
        'private_token' => env('RECOMbee_PRIVATE_TOKEN'),
        'region' => env('RECOMbee_REGION', 'us-west'),
    ],
    

    Bind the client in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            return new Client(
                config('services.recombee.database_id'),
                config('services.recombee.private_token'),
                ['region' => config('services.recombee.region')]
            );
        });
    }
    
  3. First Use Case: Fetch recommendations for a user in a Laravel controller:

    use Recombee\RecommApi\Requests as Reqs;
    
    public function showRecommendations($userId)
    {
        $client = app(Client::class);
        $response = $client->send(new Reqs\RecommendItemsToUser($userId, 5));
        return response()->json($response);
    }
    

Where to Look First

  • API Reference: Recombee Docs for request/response schemas.
  • Laravel Integration: Focus on Client initialization and Requests namespace for API calls.
  • Error Handling: Review Exceptions namespace for fallback strategies.

Implementation Patterns

Usage Patterns

  1. Real-Time Recommendations:

    • Use RecommendItemsToUser or RecommendItemsToItem for dynamic suggestions (e.g., product pages).
    • Example:
      $response = $client->send(
          new Reqs\RecommendItemsToItem('product-123', 'user-456', 3)
      );
      
  2. Batch Processing:

    • For bulk operations (e.g., importing catalogs), use Batch requests:
      $batch = new Reqs\Batch([
          new Reqs\AddItemProperty('price', 'double'),
          new Reqs\SetItemValues('item-1', ['price' => 99.99]),
      ]);
      $client->send($batch);
      
  3. Event-Driven Workflows:

    • Trigger recommendations via Laravel events (e.g., ProductViewed):
      event(new ProductViewed($productId, $userId));
      // In listener:
      $client->send(new Reqs\AddPurchase($userId, $productId));
      
  4. Personalized Search:

    • Integrate with Laravel’s search (e.g., Scout) by extending SearchItems:
      $results = $client->send(
          new Reqs\SearchItems('user-1', 'laptop', 10, ['scenario' => 'search'])
      );
      

Workflows

  1. Catalog Management:

    • Setup: Define item properties (e.g., price, category) via AddItemProperty.
    • Sync: Use SetItemValues to update product data from Laravel models:
      $item = Product::find($id);
      $client->send(new Reqs\SetItemValues(
          "product-{$item->id}",
          ['price' => $item->price, 'category' => $item->category]
      ));
      
  2. User Engagement Tracking:

    • Log interactions (e.g., purchases, clicks) asynchronously:
      $client->send(new Reqs\AddPurchase($userId, $productId));
      
  3. A/B Testing:

    • Route users to different recommendation scenarios:
      $response = $client->send(
          new Reqs\RecommendItemsToUser($userId, 5, ['scenario' => 'upsell'])
      );
      

Integration Tips

  • Laravel Queues: Offload batch requests to queues (e.g., RecommendationJob):
    RecommendationJob::dispatch($userId, $itemId)->onQueue('recommendations');
    
  • Caching: Cache recommendations (e.g., Redis) with a short TTL:
    $cacheKey = "recommendations:{$userId}";
    $recommendations = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($client, $userId) {
        return $client->send(new Reqs\RecommendItemsToUser($userId, 5));
    });
    
  • Fallbacks: Implement a fallback service (e.g., PopularItemsService) when Recombee fails:
    try {
        return $client->send(new Reqs\RecommendItemsToUser($userId, 5));
    } catch (ApiException $e) {
        return app(FallbackService::class)->getPopularItems($userId);
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • Recombee’s API may throttle requests. Monitor response times and implement exponential backoff:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = HttpClient::create([
          'base_uri' => 'https://api.recombee.com',
          'headers' => ['Authorization' => 'Bearer ' . config('services.recombee.private_token')],
          'retry_on_status' => [429, 500, 503],
          'retry_delay' => RetryStrategy::DELAY_MULTIPLICATIVE,
      ]);
      
  2. Cold Start Issues:

    • New users/items may get poor recommendations. Use cascadeCreate or pre-populate data:
      $client->send(new Reqs\AddPurchase($userId, $itemId, ['cascadeCreate' => true]));
      
  3. Data Schema Mismatches:

    • Ensure Laravel model fields match Recombee’s expected property types (e.g., double for prices, timestamp for dates).
  4. Scenario Dependency:

    • Recommendations tied to scenarios (e.g., homepage, product_detail) may behave unexpectedly if not configured in Recombee’s admin UI.

Debugging

  1. Logging:

    • Enable debug logging for API responses:
      $client->setLogger(new Monolog\Logger('recombee', [
          new Monolog\Handler\StreamHandler(storage_path('logs/recombee.log'))
      ]));
      
  2. Error Handling:

    • Catch specific exceptions for granular fallbacks:
      try {
          $response = $client->send($request);
      } catch (ApiTimeoutException $e) {
          // Retry logic
      } catch (ResponseException $e) {
          // Log and fallback
      }
      
  3. Validation:

    • Validate Recombee’s response structure before processing:
      $response = $client->send($request);
      if (!isset($response['recommendations'])) {
          throw new \RuntimeException('Invalid response format');
      }
      

Config Quirks

  1. Region Selection:

    • Choose the closest region to minimize latency (e.g., eu-central for EU users).
  2. Token Security:

    • Never hardcode tokens in PHP files. Use Laravel’s .env and config/services.php.
  3. Batch Size Limits:

    • Recombee may limit batch request sizes. Split large batches into chunks:
      $chunkSize = 100;
      foreach (array_chunk($requests, $chunkSize) as $chunk) {
          $client->send(new Reqs\Batch($chunk));
      }
      

Extension Points

  1. Custom Requests:

    • Extend the Request class to add domain-specific logic:
      class CustomRecommendRequest extends Reqs\RecommendItemsToUser
      {
          public function __construct($userId, $count, array $options = [])
          {
              $options['filter'] = "'category' IN ['electronics', 'books']";
              parent::__construct($userId, $count, $options);
          }
      }
      
  2. Response Transformers:

    • Convert Recombee responses to Laravel collections:
      $response = $client->send(new Reqs\RecommendItemsToUser($userId, 5));
      $items = collect($response['recommendations'])->map(function ($item) {
          return Product::find($item['itemId']);
      });
      
  3. Webhook Integration:

    • Use Recombee’s webhooks to sync events (e.g., Purchase) with Laravel:
      Route::post('/recombee-webhook', function (Request $request) {
          $event = json_decode($request->getContent(), true
      
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata