Documentation Index
Fetch the complete documentation index at: https://docs.neuronsearchlab.com/llms.txt
Use this file to discover all available pages before exploring further.
The PHP SDK is published on Packagist and the source lives on GitHub. Install it with Composer in Laravel or any other PHP app.
Installation
composer require neuronsearchlab/sdk-php
If you are using Laravel, this is the standard installation path. Composer pulls the package from Packagist automatically.
Initialize the client
The SDK uses a Bearer token for authentication. Obtain an access token by exchanging your SDK credentials and pass it when creating the client:
<?php
require __DIR__ . '/vendor/autoload.php';
use NeuronSearchLab\NeuronSDK;
$sdk = new NeuronSDK([
'baseUrl' => 'https://api.neuronsearchlab.com/v1',
'accessToken' => '<your_access_token>',
]);
Configuration options
| Option | Type | Default | Description |
|---|
baseUrl | string | required | API base URL |
accessToken | string | required | Bearer token from the auth token endpoint |
timeoutMs | int | 10000 | HTTP request timeout in ms |
maxRetries | int | 2 | Retry count on 429/5xx/timeouts |
collateWindowSeconds | float | 3 | Buffer events for this many seconds before flushing |
maxBatchSize | int | 200 | Flush immediately when the buffer reaches this size |
maxBufferedEvents | int | 5000 | Drop oldest events beyond this limit |
maxEventRetries | int | 5 | Retry count for buffered event sends |
disableArrayBatching | bool | false | Force single-event sends |
propagateRecommendationRequestId | bool | true | Auto-attach request_id from recommendations to subsequent events |
sessionId | string or null | null | Override the SDK-wide session ID |
autoSessionId | bool | true | Auto-generate a session UUID |
httpClient | callable | cURL | Custom HTTP transport for non-cURL environments or tests |
Get recommendations
$result = $sdk->getRecommendations([
'userId' => 'user-123',
'contextId' => '101',
'limit' => 10,
]);
var_dump($result['recommendations']);
Each recommendation includes id, object, item_id, rank, score, and an embedded item object with the metadata you stored. The response also includes a request_id for event attribution.
Auto-generated sections
Use getAutoRecommendations for paginated, auto-titled recommendation sections:
$section = $sdk->getAutoRecommendations([
'userId' => 'user-123',
'limit' => 5,
'windowDays' => 7,
]);
if (!empty($section['next_cursor'])) {
$next = $sdk->getAutoRecommendations([
'userId' => 'user-123',
'cursor' => $section['next_cursor'],
]);
}
Track events
Events provide the feedback loop that powers personalization. The PHP SDK buffers events in memory for the lifetime of the current process.
$sdk->trackEvent([
'type' => 'click',
'userId' => 'user-123',
'itemId' => 'itm_7f3a2c9e',
])->wait();
How batching works in PHP
Buffer events
Events are buffered with a timestamp that maps to occurred_at in the API.
Flush at max batch size
The buffer flushes when it reaches maxBatchSize.
Force delivery when needed
You can force delivery with flushEvents() or by calling ->wait() on the returned PendingResult.
Flush during shutdown
Remaining buffered events are flushed during PHP shutdown.
Retry failed sends
Failed sends are retried with exponential backoff.
$pending = $sdk->trackEvent([
'type' => 'view',
'userId' => 'user-123',
'itemId' => 'itm_7f3a2c9e',
]);
$pending->wait();
$sdk->flushEvents();
Request ID propagation
When propagateRecommendationRequestId is enabled, the SDK captures the request_id from getRecommendations() and automatically attaches it to subsequent trackEvent() calls unless you explicitly provide requestId or request_id.
$recs = $sdk->getRecommendations([
'userId' => 'user-123',
'limit' => 5,
]);
$sdk->trackEvent([
'type' => 'click',
'userId' => 'user-123',
'itemId' => $recs['recommendations'][0]['item_id'],
])->wait();
Manage catalog items
Create an item
$sdk->upsertItem([
'itemId' => 'itm_7f3a2c9e',
'name' => 'Nike Running Shoes',
'description' => 'High-performance running shoes for daily training.',
'metadata' => [
'category' => 'Footwear',
'brand' => 'Nike',
'price' => 109.99,
],
]);
Update an item
$sdk->patchItem([
'itemId' => 'itm_7f3a2c9e',
'active' => false,
]);
Or use the convenience helper:
$sdk->setItemActive('itm_7f3a2c9e', false);
Delete items
$sdk->deleteItems(['itemId' => 'itm_7f3a2c9e']);
$sdk->deleteItems([
['itemId' => 'itm_7f3a2c9e'],
['itemId' => 'itm_a8d1b247'],
]);
Error handling
The SDK exposes SDKHttpError and SDKTimeoutError:
<?php
use NeuronSearchLab\SDKHttpError;
use NeuronSearchLab\SDKTimeoutError;
try {
$sdk->getRecommendations(['userId' => 'user-123']);
} catch (SDKHttpError $error) {
error_log(sprintf('HTTP %d: %s', $error->status, $error->statusText));
} catch (SDKTimeoutError $error) {
error_log(sprintf('Request timed out after %dms', $error->timeoutMs));
}
Transient errors such as 429s, 5xxs, and timeouts are retried automatically.
Logging
Configure structured logging for debugging and observability:
<?php
use function NeuronSearchLab\configureLogger;
configureLogger([
'level' => 'DEBUG',
'enableNetworkBodyLogging' => true,
'enablePerformanceLogging' => true,
]);
Available log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
Session management
The SDK auto-generates a session UUID on initialization when autoSessionId is enabled. You can override or read it:
$sdk->setSessionId('custom-session-id');
var_dump($sdk->getSessionId());
Links