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 Setup

  1. Install the Package

    composer require recombee/php-api-client
    

    Add to composer.json if preferred:

    "recombee/php-api-client": "^6.2.0"
    
  2. Configure API Credentials Add to .env:

    RECOMbee_DATABASE_ID=your_database_id
    RECOMbee_PRIVATE_TOKEN=your_private_token
    RECOMbee_REGION=us-west  # or ap-se, eu-central, etc.
    
  3. Basic Client Initialization In a service or controller:

    use Recombee\RecommApi\Client;
    
    $client = new Client(
        config('services.recombee.database_id'),
        config('services.recombee.private_token'),
        ['region' => config('services.recombee.region')]
    );
    
  4. First Use Case: Fetch Recommendations

    use Recombee\RecommApi\Requests as Reqs;
    
    $response = $client->send(new Reqs\RecommendItemsToUser('user-123', 5));
    return $response['recommendedItems']; // Array of recommended items
    

Implementation Patterns

Core Workflows

1. Data Ingestion

  • Batch Processing for Efficiency Use Batch requests for bulk operations (e.g., adding purchases, setting item properties):

    $batchRequests = collect($purchases)->map(function ($purchase) {
        return new Reqs\AddPurchase($purchase['userId'], $purchase['itemId'], ['cascadeCreate' => true]);
    });
    
    $client->send(new Reqs\Batch($batchRequests->toArray()));
    
  • Laravel Integration with Eloquent Sync database records to Recombee using Laravel events:

    // app/Events/PurchaseCreated.php
    class PurchaseCreated implements ShouldBroadcast
    {
        public function handle()
        {
            $client->send(new Reqs\AddPurchase($this->userId, $this->itemId));
        }
    }
    

2. Recommendation Strategies

  • User-Based Recommendations

    $recommendations = $client->send(
        new Reqs\RecommendItemsToUser('user-42', 10, ['scenario' => 'homepage'])
    );
    
  • Item-Based Recommendations (e.g., "Frequently Bought Together")

    $recommendations = $client->send(
        new Reqs\RecommendItemsToItem('product-789', 'user-42', 5, [
            'filter' => "'category' = 'electronics' AND 'price' > 100"
        ])
    );
    
  • Search-Based Recommendations

    $searchResults = $client->send(
        new Reqs\SearchItems('user-42', 'wireless headphones', 8, [
            'scenario' => 'search_results'
        ])
    );
    

3. Dynamic Filtering and Personalization

  • Context-Aware Filters Use context_item or context_user in filters:

    $recommendations = $client->send(
        new Reqs\RecommendItemsToItem('product-123', 'user-42', 3, [
            'filter' => "'price' < context_item[\"price\"] * 1.5" // Up to 50% more expensive
        ])
    );
    
  • Scenario-Based Recommendations Define scenarios in Recombee’s admin UI and reference them:

    $recommendations = $client->send(
        new Reqs\RecommendItemsToUser('user-42', 5, ['scenario' => 'cart_upsell'])
    );
    

4. Pagination and Infinite Scroll

  • Fetch Next Batch of Recommendations
    $firstBatch = $client->send(new Reqs\RecommendItemsToUser('user-42', 5));
    $nextBatch = $client->send(new Reqs\RecommendNextItems($firstBatch['recommId'], 5));
    

Laravel-Specific Patterns

Service Provider Binding

Register the client as a singleton in AppServiceProvider:

public function register()
{
    $this->app->singleton(RecommendationService::class, function ($app) {
        return new Client(
            config('services.recombee.database_id'),
            config('services.recombee.private_token'),
            ['region' => config('services.recombee.region')]
        );
    });
}

API Resource Transformation

Use Laravel’s ApiResource to shape responses:

// app/Http/Resources/RecommendedItem.php
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'score' => $this->score,
        'url' => route('products.show', $this->id),
    ];
}

Caching Recommendations

Cache responses to reduce API calls:

$recommendations = Cache::remember("recommendations_user_{$userId}", now()->addHours(1), function () use ($userId) {
    return $client->send(new Reqs\RecommendItemsToUser($userId, 10));
});

Queue-Based Processing

Offload heavy operations to queues:

// Dispatch a job to update recommendations
UpdateRecommendationsJob::dispatch($userId, $itemId);

// Job handler
public function handle()
{
    $client->send(new Reqs\AddPurchase($this->userId, $this->itemId));
}

Gotchas and Tips

Common Pitfalls

1. Rate Limiting and Throttling

  • Issue: Recombee’s API may throttle requests during peak times.
  • Solution:
    • Implement exponential backoff in your client wrapper:
      use Illuminate\Support\Facades\Http;
      
      $response = Http::retry(3, 100)->post($url, $data);
      
    • Use Laravel’s queue:work to distribute load.

2. Cold Start Problems

  • Issue: New users/items may get poor recommendations.
  • Solution:
    • Use cascadeCreate: true to auto-create entities:
      $client->send(new Reqs\AddPurchase('new-user', 'new-item', ['cascadeCreate' => true]));
      
    • Configure Recombee’s cold-start strategies in the admin UI (e.g., popularity-based fallbacks).

3. Data Mismatch Errors

  • Issue: Invalid item/user IDs or malformed properties cause ApiException.
  • Solution:
    • Validate data before sending:
      if (!preg_match('/^[a-z0-9\-]+$/', $itemId)) {
          throw new \InvalidArgumentException("Invalid item ID format");
      }
      
    • Use Laravel’s Form Request validation:
      public function rules()
      {
          return [
              'user_id' => 'required|string|max:255',
              'item_id' => 'required|string|max:255',
          ];
      }
      

4. Region-Specific Latency

  • Issue: Recommendations may feel slow if the region is far from your users.
  • Solution:
    • Choose the closest Recombee region (e.g., us-west for US users, eu-central for EU).
    • Cache recommendations aggressively for high-latency regions.

5. Scenario Misconfiguration

  • Issue: Recommendations don’t match expectations due to misconfigured scenarios.
  • Solution:
    • Test scenarios in Recombee’s Admin UI before relying on them in code.
    • Log scenario names for debugging:
      \Log::info("Fetching recommendations for scenario: {$scenario}");
      

Debugging Tips

Logging API Responses

Wrap the client to log requests/responses:

$client = new Client($dbId, $token, ['region' => 'us-west']);
$client->setLogger(function ($request, $response) {
    \Log::debug('Recombee API Request', [
        'request' => $request->getBody(),
        'response' => $response->getBody(),
    ]);
});

Handling Exceptions Gracefully

Use Laravel’s exception handling to log and fallback:

use Recombee\RecommApi\Exceptions\ApiException;

try {
    $recommendations = $client->send(new Reqs\RecommendItemsToUser($userId, 5));
} catch (ApiException $e) {
    \Log::error("Recombee API failed: {$e->getMessage()}");
    return response()->json(['fallback' => true, 'items' => []], 200);
}

Monitoring API Usage

Track API calls to avoid hitting limits:

// In a middleware or service
public function handle()
{
    $this->incrementRecombeeApiCalls();
    if ($this->recombeeApiCalls
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