> ## 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.

# PHP SDK

> Install, configure, and use the official NeuronSearchLab PHP SDK in Laravel or any PHP application.

<Note>
  The PHP SDK is published on [Packagist](https://packagist.org/packages/neuronsearchlab/sdk-php) and the source lives on [GitHub](https://github.com/NeuronSearchLab/neuronsearchlab-sdk-php). Install it with Composer in Laravel or any other PHP app.
</Note>

## Installation

```bash theme={null}
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](/authentication) and pass it when creating the client:

```php theme={null}
<?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

```php theme={null}
$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.

## Search

Use `search` when the user supplies a free-text query and you want ranked catalog items back through the Core API data plane:

```php theme={null}
$results = $sdk->search([
    'query' => 'waterproof trail shoes',
    'userId' => 'user-123',
    'contextId' => '101',
    'limit' => 10,
    'filter' => ['category:footwear'],
]);

var_dump($results['data']);
```

The SDK posts to `https://api.neuronsearchlab.com/v1/search`, not the console Platform API. Search responses use the same item shape as recommendations and include `query`, `request_id`, `data`, and `recommendations`.

### Auto-generated sections

Use `getAutoRecommendations` for paginated, auto-titled recommendation sections:

```php theme={null}
$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.

```php theme={null}
$sdk->trackEvent([
    'type' => 'click',
    'userId' => 'user-123',
    'itemId' => '7f3a2c9e',
])->wait();
```

### How batching works in PHP

<Steps>
  <Step title="Buffer events">
    Events are buffered with a timestamp that maps to `occurred_at` in the API.
  </Step>

  <Step title="Flush at max batch size">
    The buffer flushes when it reaches `maxBatchSize`.
  </Step>

  <Step title="Force delivery when needed">
    You can force delivery with `flushEvents()` or by calling `->wait()` on the returned `PendingResult`.
  </Step>

  <Step title="Flush during shutdown">
    Remaining buffered events are flushed during PHP shutdown.
  </Step>

  <Step title="Retry failed sends">
    Failed sends are retried with exponential backoff.
  </Step>
</Steps>

```php theme={null}
$pending = $sdk->trackEvent([
    'type' => 'view',
    'userId' => 'user-123',
    'itemId' => '7f3a2c9e',
]);

$pending->wait();

$sdk->flushEvents();
```

### Request ID propagation

When `propagateRecommendationRequestId` is enabled, the SDK captures the `request_id` from `getRecommendations()` or `search()` and automatically attaches it to subsequent `trackEvent()` calls unless you explicitly provide `requestId` or `request_id`.

```php theme={null}
$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

```php theme={null}
$sdk->upsertItem([
    'itemId' => '7f3a2c9e',
    'name' => 'Nike Running Shoes',
    'description' => 'High-performance running shoes for daily training.',
    'metadata' => [
        'category' => 'Footwear',
        'brand' => 'Nike',
        'price' => 109.99,
    ],
]);
```

### Update an item

```php theme={null}
$sdk->patchItem([
    'itemId' => '7f3a2c9e',
    'active' => false,
]);
```

Or use the convenience helper:

```php theme={null}
$sdk->setItemActive('7f3a2c9e', false);
```

### Delete items

```php theme={null}
$sdk->deleteItems(['itemId' => '7f3a2c9e']);

$sdk->deleteItems([
    ['itemId' => '7f3a2c9e'],
    ['itemId' => 'a8d1b247'],
]);
```

***

## Error handling

The SDK exposes `SDKHttpError` and `SDKTimeoutError`:

```php theme={null}
<?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 theme={null}
<?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:

```php theme={null}
$sdk->setSessionId('custom-session-id');
var_dump($sdk->getSessionId());
```

***

## Links

* [Install from Packagist](https://packagist.org/packages/neuronsearchlab/sdk-php)
* [Source on GitHub](https://github.com/NeuronSearchLab/neuronsearchlab-sdk-php)
* [Core API reference](/api-reference/introduction)
* [JavaScript SDK](/sdk/introduction)
