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.
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')]
);
});
}
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);
}
Client initialization and Requests namespace for API calls.Exceptions namespace for fallback strategies.Real-Time Recommendations:
RecommendItemsToUser or RecommendItemsToItem for dynamic suggestions (e.g., product pages).$response = $client->send(
new Reqs\RecommendItemsToItem('product-123', 'user-456', 3)
);
Batch Processing:
Batch requests:
$batch = new Reqs\Batch([
new Reqs\AddItemProperty('price', 'double'),
new Reqs\SetItemValues('item-1', ['price' => 99.99]),
]);
$client->send($batch);
Event-Driven Workflows:
ProductViewed):
event(new ProductViewed($productId, $userId));
// In listener:
$client->send(new Reqs\AddPurchase($userId, $productId));
Personalized Search:
SearchItems:
$results = $client->send(
new Reqs\SearchItems('user-1', 'laptop', 10, ['scenario' => 'search'])
);
Catalog Management:
price, category) via AddItemProperty.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]
));
User Engagement Tracking:
$client->send(new Reqs\AddPurchase($userId, $productId));
A/B Testing:
$response = $client->send(
new Reqs\RecommendItemsToUser($userId, 5, ['scenario' => 'upsell'])
);
RecommendationJob):
RecommendationJob::dispatch($userId, $itemId)->onQueue('recommendations');
$cacheKey = "recommendations:{$userId}";
$recommendations = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($client, $userId) {
return $client->send(new Reqs\RecommendItemsToUser($userId, 5));
});
PopularItemsService) when Recombee fails:
try {
return $client->send(new Reqs\RecommendItemsToUser($userId, 5));
} catch (ApiException $e) {
return app(FallbackService::class)->getPopularItems($userId);
}
Rate Limiting:
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,
]);
Cold Start Issues:
cascadeCreate or pre-populate data:
$client->send(new Reqs\AddPurchase($userId, $itemId, ['cascadeCreate' => true]));
Data Schema Mismatches:
double for prices, timestamp for dates).Scenario Dependency:
homepage, product_detail) may behave unexpectedly if not configured in Recombee’s admin UI.Logging:
$client->setLogger(new Monolog\Logger('recombee', [
new Monolog\Handler\StreamHandler(storage_path('logs/recombee.log'))
]));
Error Handling:
try {
$response = $client->send($request);
} catch (ApiTimeoutException $e) {
// Retry logic
} catch (ResponseException $e) {
// Log and fallback
}
Validation:
$response = $client->send($request);
if (!isset($response['recommendations'])) {
throw new \RuntimeException('Invalid response format');
}
Region Selection:
eu-central for EU users).Token Security:
.env and config/services.php.Batch Size Limits:
$chunkSize = 100;
foreach (array_chunk($requests, $chunkSize) as $chunk) {
$client->send(new Reqs\Batch($chunk));
}
Custom Requests:
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);
}
}
Response Transformers:
$response = $client->send(new Reqs\RecommendItemsToUser($userId, 5));
$items = collect($response['recommendations'])->map(function ($item) {
return Product::find($item['itemId']);
});
Webhook Integration:
Purchase) with Laravel:
Route::post('/recombee-webhook', function (Request $request) {
$event = json_decode($request->getContent(), true
How can I help you explore Laravel packages today?