Skip to main content
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',
    'accessToken' => '<your_access_token>',
]);

Configuration options

OptionTypeDefaultDescription
baseUrlstringrequiredAPI base URL
accessTokenstringrequiredBearer token from /auth/token
timeoutMsint10000HTTP request timeout in ms
maxRetriesint2Retry count on 429/5xx/timeouts
collateWindowSecondsfloat3Buffer events for this many seconds before flushing
maxBatchSizeint200Flush immediately when the buffer reaches this size
maxBufferedEventsint5000Drop oldest events beyond this limit
maxEventRetriesint5Retry count for buffered event sends
disableArrayBatchingboolfalseForce single-event sends
propagateRecommendationRequestIdbooltrueAuto-attach request_id from recommendations to subsequent events
sessionIdstring or nullnullOverride the SDK-wide session ID
autoSessionIdbooltrueAuto-generate a session UUID
httpClientcallablecURLCustom HTTP transport for non-cURL environments or tests

Get recommendations

$result = $sdk->getRecommendations([
    'userId' => 'user-123',
    'contextId' => 'homepage',
    'limit' => 10,
]);

var_dump($result['recommendations']);
Each recommendation includes entity_id, name, description, score, and any metadata you stored with the item. 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([
    'eventId' => 1,
    'userId' => 'user-123',
    'itemId' => 'item-456',
])->wait();

How batching works in PHP

  1. Events are buffered with a client_ts timestamp.
  2. The buffer flushes when it reaches maxBatchSize.
  3. You can force delivery with flushEvents() or by calling ->wait() on the returned PendingResult.
  4. Remaining buffered events are flushed during PHP shutdown.
  5. Failed sends are retried with exponential backoff.
$pending = $sdk->trackEvent([
    'eventId' => 2,
    'userId' => 'user-123',
    'itemId' => 'item-456',
]);

$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([
    'eventId' => 1,
    'userId' => 'user-123',
    'itemId' => $recs['recommendations'][0]['entity_id'],
])->wait();

Manage catalog items

Upsert an item

$sdk->upsertItem([
    'itemId' => 'item-456',
    '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' => 'item-456',
    'active' => false,
]);
Or use the convenience helper:
$sdk->setItemActive('item-456', false);

Delete items

$sdk->deleteItems(['itemId' => 'item-456']);

$sdk->deleteItems([
    ['itemId' => 'item-456'],
    ['itemId' => 'item-789'],
]);

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());