Install the Package
composer require recombee/php-api-client
Add to composer.json if preferred:
"recombee/php-api-client": "^6.2.0"
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.
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')]
);
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
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));
}
}
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'
])
);
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'])
);
$firstBatch = $client->send(new Reqs\RecommendItemsToUser('user-42', 5));
$nextBatch = $client->send(new Reqs\RecommendNextItems($firstBatch['recommId'], 5));
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')]
);
});
}
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),
];
}
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));
});
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));
}
use Illuminate\Support\Facades\Http;
$response = Http::retry(3, 100)->post($url, $data);
queue:work to distribute load.cascadeCreate: true to auto-create entities:
$client->send(new Reqs\AddPurchase('new-user', 'new-item', ['cascadeCreate' => true]));
ApiException.if (!preg_match('/^[a-z0-9\-]+$/', $itemId)) {
throw new \InvalidArgumentException("Invalid item ID format");
}
public function rules()
{
return [
'user_id' => 'required|string|max:255',
'item_id' => 'required|string|max:255',
];
}
us-west for US users, eu-central for EU).\Log::info("Fetching recommendations for scenario: {$scenario}");
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(),
]);
});
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);
}
Track API calls to avoid hitting limits:
// In a middleware or service
public function handle()
{
$this->incrementRecombeeApiCalls();
if ($this->recombeeApiCalls
How can I help you explore Laravel packages today?