---
source_url: https://www.pubnub.com/docs/sdks/php/api-reference/data-sync
title: DataSync API for PHP SDK
updated_at: 2026-10-05T14:28:43.000Z
sdk_name: PubNub PHP SDK
sdk_version: 10.0.0
---

# DataSync API for PHP SDK

PubNub PHP SDK, use the latest version: 10.0.0

Install:

```bash
composer require pubnub/pubnub@10.0.0
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

[DataSync](https://www.pubnub.com/docs/data-storage/structured-data/overview.md) is PubNub's data layer for storing application state (users, channels, memberships, and any custom object type) and keeping every connected client current through real-time events. Use it to model the objects your application works with and to react the moment they change.

DataSync is the successor to [App Context](https://www.pubnub.com/docs/sdks/php/api-reference/objects.md).

:::note DataSync entities and SDK entities are different things
This page is about **DataSync entities**, the records the service stores and treats as the source of truth for your application state. They are created and read through the `$pubnub->dataSync()->*` methods documented here.
The PHP SDK has no client-side SDK entity concept. A channel ID is just the string you pass to `channels()` when you subscribe, it carries no stored state of its own. To observe a DataSync object in real time, subscribe to its channel and attach a DataSync listener to the PubNub client, as described in [Real-time updates](#real-time-updates).
:::

The classes that your objects conform to (their types and schemas) are defined through the Admin API or the [Admin Portal](https://admin.pubnub.com/), not through this SDK:

* Entity classes, which back users, channels, and custom entities: [list](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), [read](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-entity-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-entity-class-by-id.md). Partial updates aren't implemented; replace the complete class version instead.
* Relationship classes, which back memberships and custom relationships: [list](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), [read](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md), [create](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md), [replace](https://www.pubnub.com/docs/admin-api/update-relationship-class-with-complete-resource-replacement.md), and [delete](https://www.pubnub.com/docs/admin-api/delete-relationship-class-by-name-and-version.md).

`User` and `Channel` entity classes and the `Membership` relationship class are predefined on every keyset, so you only need to define classes for your own custom entities and relationships.

A class definition is what decides, for every object of that class, which `payload` fields are filterable and sortable, which [projection](https://www.pubnub.com/docs/sdks/php/api-reference/access-manager.md#grant-token) each field belongs to, and how long the object lives before it expires. Refer to [managing classes](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#managing-classes) for more information.

Every method returns a typed result from `sync()`, or a `PNEnvelope` from `envelope()` that carries the result and the status side by side. The single-object methods return a result whose `getData()` holds the record, with `getId()` and `getETag()` as shortcuts. The list methods return a result whose `getData()` holds an array of records, with `count()` and `getPage()` for the pagination details. The `deleteUser`, `deleteChannel`, `deleteMembership`, `deleteEntity`, and `deleteRelationship` methods return a `PNDataSyncDeleteResult` that carries no data. The `status` key in each Response block below stands for the HTTP status code, which `envelope()` exposes through `getStatus()->getStatusCode()`, and the result doesn't surface the HATEOAS `links` the service adds to a response. A stored object carries its free-form `status` and its `expiresAt` auto-deletion timestamp (ISO 8601) whenever those are set on it, and the timestamps stay ISO 8601 strings rather than becoming `DateTime` objects.

### Authorization

Every DataSync request must be [authorized](https://www.pubnub.com/docs/data-storage/structured-data/access-control.md#authorizing-requests) with a token or signature. A request with no credential fails with a `401`; an invalid credential or a credential that doesn't permit the operation fails with a `403`.

A signature means the client is configured with a secret key, and the SDK then signs every request with it automatically. Never put a secret key in a client-side application, use it only on a server you control. Give client-side applications a token from `grantToken()` instead, set with `setToken()`.

### Pagination

DataSync pagination is **forward-only**. There is no previous-page cursor, and `PNDataSyncPage` exposes no previous cursor or `hasPrev`. To revisit an earlier page, page from the start again.

All list methods (`getUsers`, `getChannels`, `getMemberships`, `getEntities`, and `getRelationships`) accept `cursor` and `limit` (default `20`, max `100`) and can return a `PNDataSyncPage` from `getPage()` with `hasNext()`, `getNextCursor()`, and `getLimit()`. The page is optional, so guard the access when you read it, for example `$result->getPage()?->getNextCursor()`.

To page forward, pass the returned `getNextCursor()` value back as `cursor` on the next call, and stop when `hasNext()` is `false`. `getNextCursor()` is `null` on the last page. Refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination) for details.

### Filtering and sorting

All list methods accept two mutually exclusive filter parameters, `filterFast` and `filter`. The SDK sends whatever you set, so a call that carries both reaches the server and fails there with a `400`.

| Parameter | Consistency | Properties it can read | Expression complexity |
| --- | --- | --- | --- |
| `filterFast` | Strongly consistent, reflects the latest writes | Filtering mode `simple` or `full` | Up to 10 conditions by default (raisable per keyset) |
| `filter` | Eventually consistent, results can briefly lag writes | Filtering mode `full` only | Full expression language |

Reach for `filterFast` when the query has to see an object you just wrote, and for `filter` when you need the full expression language over a `full`-indexed property.

:::warning danger
filter
is not the strongly consistent one
The two names read the wrong way round if you assume `filter` is the basic option. `filterFast` is the strongly consistent, limited one. `filter` is the richer, eventually consistent one.
:::

Both parameters share the same expression language, a string built from a property name, an operator, and a value:

| Operators |  |
| --- | --- |
| Comparison | `==`, `!=`, `<`, `>`, `<=`, `>=` |
| Pattern matching | `LIKE` (case-insensitive), `SLIKE` (case-sensitive), `ILIKE` (case-insensitive, same as `LIKE`) |
| Logical | `&&`, `||`, `!`, and parentheses for grouping |

Values are quoted strings, numbers, `true`, `false`, or `null`. Pattern operators (`LIKE`, `SLIKE`, `ILIKE`) apply to string properties only, and `null` is only valid with `==` and `!=`. Reference a property by its `name`, not its declared `path`, and only properties declared on the class are filterable. To reach a nested `payload` property, declare it as a class property first, then filter by that property's `name`, for example `'price < 100'` for a `product` class that declares `price`.

Some examples:

```php
->filterFast('price < 100')                               // strongly consistent, single condition
->filterFast('(price < 100 && stock > 0) || price > 500') // strongly consistent, grouped conditions
->filter('name LIKE "*sneaker*"')                         // eventually consistent, needs filtering mode "full"
->filter('!(status == "discontinued")')                   // eventually consistent, negated condition
```

Both parameters only work over properties declared on the class, plus the built-in `id`, `createdAt`, `updatedAt`, and `status` fields, which are always filterable and sortable without being declared. `eTag` and `expiresAt` are neither. The `status` exception does not hold if the class redeclares `/status` scoped to projections your token cannot fully reach. Refer to [filtering](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#filtering) for the two filtering tiers, and [property definitions](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#property-definitions) for how properties are declared.

Use `sort` to order results. Its value is a comma-separated list of fields, each a property name optionally suffixed with `:asc` or `:desc`. A bare name sorts ascending:

```php
->sort('price:desc')       // single field, descending
->sort('type,price:desc')  // type ascending, then price descending
->sort('createdAt:asc')    // explicit ascending
```

`sort` also accepts an array that the SDK joins into that string. A key is a property name and its value is `'asc'` or `'desc'`, and a bare list entry sorts ascending. Fields are joined in the order they appear:

```php
->sort(['type', 'price' => 'desc']) // same order as 'type,price:desc'
```

The `+field` and `-field` prefixes are **not** accepted. A leading `-` is read as part of the property name, so `'-price'` fails with a `400`. Only properties declared on the class with a filtering mode other than `none` can be sorted on when sorting alone or alongside `filterFast`. Sorting alongside `filter` additionally requires the field to be declared `full`. The built-in fields `id`, `createdAt`, `updatedAt`, and `status` are always sortable without declaring them on the class.

The SDK doesn't validate `filterFast`, `filter`, or `limit` locally, it passes them through as-is, and it passes a `sort` string through untouched. An invalid expression, an unsortable field, or an out-of-range `limit` only surfaces as an error response from the server. The one exception is an array `sort` whose direction is neither `asc` nor `desc`, which throws a `PubNubValidationException` before anything is sent, because the server would otherwise silently drop the direction and sort the other way.

### Concurrency (ETag)

Every stored object carries an `ETag`. To guard against concurrent writes, pass the `ETag` you read earlier as `ifMatchesETag` on `set*`, `update*`, and `delete*` calls. The SDK sends it as the `If-Match` request header.

If the server-side value has changed in the meantime, the operation fails with a `412`, and you should re-read the object and retry. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for details.

With `sync()`, the `412` arrives as a `PubNubServerException`, and `getStatusCode()` returns it.

### Partial updates

The `update*` methods apply a partial update using raw JSON Patch (RFC 6902). Build the operations by chaining `add`, `remove`, `replace`, `move`, `copy`, and `test` on a `PNDataSyncPatch` and pass it to `patch`, or pass a raw array of operations instead. Each raw operation has an `op` (`add`, `remove`, `replace`, `move`, `copy`, or `test`), a `path` (a full JSON Pointer, for example `/status` or `/payload/price`), and, depending on the operation, a `value` or a `from`.

Each path is a full JSON Pointer (RFC 6901) and is sent as you write it. The SDK does **not** add a `/payload` prefix. To target a field inside `payload`, include the prefix yourself, for example `/payload/price`, not `/price`. A bare `/price` targets a top-level field named `price`, which doesn't exist. Top-level fields like `/status` can be patched directly. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for details.

Correct patch forms:

```php
->add('/payload/tags', 'sale')                // adds a value inside payload.tags
->replace('/payload/price', 79.99)            // replaces payload.price
->remove('/payload/tempFlag')                 // removes payload.tempFlag
->move('/payload/oldTag', '/payload/tag')
->copy('/payload/price', '/payload/msrp')
->test('/status', 'active')                   // fails the patch if the current value doesn't match
```

`move` and `copy` take the source pointer first and the target pointer second, instead of a value. `test` fails the entire patch if the current value at its path doesn't match, use it to guard the rest of the operations against a stale read.

Paths address the object's stored property names, the same keys that come back in responses. The class version is `entityClassVersion` on users, channels, and entities, and `relationshipClassVersion` on memberships and relationships. The fields set at creation cannot be patched: `entityClass` and `entityClassLevel` on users, channels, and entities, `relationshipClass`, `entityAId`, and `entityBId` on relationships, and `userId` and `channelId` on memberships.

All operations in the call apply together or not at all.

The `patch` must contain at least one operation. The SDK checks this before it sends anything and throws a `PubNubValidationException` if the builder is empty or the array has no operations. For a raw array, it also checks that every operation has an `op` and a `path`, a `value` for `add`, `replace`, and `test`, and a `from` for `move` and `copy`.

### Expiry (TTL)

An object's `expiresAt` is computed once when the object is created, and updates never refresh it. The value is the creation time plus the class TTL, rounded up to the start of the next whole UTC day, so it rarely lands exactly one TTL from the moment you wrote the object.

Entity classes you create default to a 31-day TTL, while the built-in Global `User` and `Channel` classes use 30 days. TTL cannot be disabled. A relationship expires at the earlier expiry time of the two entities it links, fixed when the relationship is created.

Refer to [data expiry](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#data-expiry-ttl) for details.

:::note Synchronous calls, two ways to read the outcome
Every DataSync method is a fluent builder that you finish with `sync()` or `envelope()`, and the request blocks until it completes. `sync()` returns the typed result and throws on failure: a `PubNubValidationException` for a missing or invalid argument, checked before anything is sent (for example a missing id, an `entityClassVersion` below `1`, or a missing `entityClass` on entities), and a `PubNubServerException` when the service answers with an error, where `getStatusCode()` returns the HTTP status. `envelope()` returns a `PNEnvelope` and never throws for a server error, so call `isError()` first, then read `getResult()` or `getStatus()`. It also skips the argument checks, so the service rejects an invalid request instead. The samples use `sync()`.
:::

:::note Requires Access Manager
DataSync requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

## Users

Users are built-in objects. There are no top-level `name` or `email` fields, all application data lives in the free-form `payload`. Refer to [users](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#users) for the concept.

A user is an entity of the built-in `User` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. To give your users their own declared, filterable properties, define a subclass of `User` with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) and pass its name as `entityClass`.

### Create user

Creates a user. Supply an `userId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```php
$pubnub->dataSync()->createUser()
    ->userId(string)
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->status(string)
    ->payload(array)
    ->sync(); // PNDataSyncUserResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Optional | `server-generated` | User identifier. Omit to let the server generate a UUID. Max 255 characters. |
| entityClass | string | Optional | `User` | Name of the entity class this user belongs to. Must be `User` or one of its subclasses. Defaults to `User` on the server if omitted. Set at creation and immutable afterward. |
| entityClassVersion | int | Yes |  | Version of the user class schema. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->createUser()
    ->userId('user-alice')
    ->entityClassVersion(1)
    ->payload(['name' => 'Alice', 'type' => 'shopper'])
    ->sync();

printf("Created %s with ETag %s\n", $result->getId(), $result->getETag());
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get user

Returns a single user by `userId`.

#### Method(s)

```php
$pubnub->dataSync()->getUser()
    ->userId(string)
    ->sync(); // PNDataSyncUserResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getUser()
    ->userId('user-alice')
    ->sync();

printf("Fetched %s\n", $result->getId());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T09:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Get all users

Returns a paginated list of users. All parameters are optional, so you can call `getUsers` and finish with `sync()` straight away. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```php
$pubnub->dataSync()->getUsers()
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->cursor(string)
    ->limit(int)
    ->filterFast(string)
    ->filter(string)
    ->sort(string|array)
    ->sync(); // PNDataSyncUsersResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityClass | string | Optional | `all user classes` | User class to list. Omit to list the Global `User` class and all of its subclasses. |
| entityClassVersion | int | Optional | `all versions` | User class version to list. Omit to list users across every version of the class. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of users per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string \| array | Optional |  | Order results. Pass a string of fields each optionally suffixed with `:asc` or `:desc`, or an array that the SDK joins into one, for example `'createdAt:desc'`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getUsers()
    ->sync();

printf("Fetched %d users\n", $result->count());
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "user-alice",
            "entityClass": "User",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Alice", "type": "shopper" },
            "createdAt": "2026-07-13T09:00:00.000Z",
            "updatedAt": "2026-07-13T09:00:00.000Z",
            "eTag": "AbCdEfGhIjKlMn"
        }
    ],
    "meta": {
        "next_cursor": "b2Zmc2V0PTIw",
        "has_next": true,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getUsers()
    ->filterFast('type == "shopper"')
    ->sync();

printf("Found %d users\n", $result->count());
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getUsers()
    ->filter('name LIKE "*Alice*"')
    ->sync();

printf("Found %d users\n", $result->count());
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getPage()->getNextCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getPage()->hasNext()` is `false`.

```php
$cursor = null;

do {
    $request = $pubnub->dataSync()->getUsers()
        ->limit(50);

    if ($cursor !== null) {
        $request->cursor($cursor);
    }

    $result = $request->sync();

    foreach ($result->getData() as $item) {
        printf("%s\n", $item->getId());
    }

    $page = $result->getPage();
    $cursor = $page !== null && $page->hasNext() ? $page->getNextCursor() : null;
} while ($cursor !== null);
```

### Set user

Replaces a user in full (PUT). Send the complete set of fields, any field you omit is cleared. `entityClass` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesETag`. For a partial update, use [Update user](#update-user).

#### Method(s)

```php
$pubnub->dataSync()->setUser()
    ->userId(string)
    ->entityClassVersion(int)
    ->status(string)
    ->payload(array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncUserResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| entityClassVersion | int | Yes |  | Version of the user class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->setUser()
    ->userId('user-alice')
    ->entityClassVersion(1)
    ->payload(['name' => 'Alice B.', 'type' => 'shopper'])
    ->sync();

printf("Replaced user, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:15:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Update user

Applies a partial update to a user with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```php
$pubnub->dataSync()->updateUser()
    ->userId(string)
    ->patch(PNDataSyncPatch|array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncUserResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| patch | PNDataSyncPatch \| array | Yes |  | One or more JSON Patch operations. Must contain at least one item. Pass a `PNDataSyncPatch` builder or a raw array of RFC 6902 operations. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$patch = (new PNDataSyncPatch())
    ->replace('/payload/name', 'Alice B.');

$result = $pubnub->dataSync()->updateUser()
    ->userId('user-alice')
    ->patch($patch)
    ->sync();

printf("Patched user, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "user-alice",
        "status": "active",
        "entityClass": "User",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Alice B.", "type": "shopper" },
        "createdAt": "2026-07-13T09:00:00.000Z",
        "updatedAt": "2026-07-13T10:20:00.000Z",
        "eTag": "EfGhIjKlMnOpQr"
    }
}
```

### Remove user

Deletes a user by `userId`.

#### Method(s)

```php
$pubnub->dataSync()->deleteUser()
    ->userId(string)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncDeleteResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Yes |  | User identifier. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$pubnub->dataSync()->deleteUser()
    ->userId('user-alice')
    ->sync();
```

#### Response

```json
{
    "status": 200
}
```

## Channels

Channels work like users. They have no top-level `name` field, all application data lives in `payload`, and they support the same operations. Refer to [channels](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#channels) for the concept.

A channel is an entity of the built-in `Channel` [entity class](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md), which the service provides at the `Global` class level. Subclass it with [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to add declared properties, then pass the subclass name as `entityClass`.

### Create channel

Creates a channel. Supply an `channelId` to control the identifier, or omit it to let the server generate one.

#### Method(s)

```php
$pubnub->dataSync()->createChannel()
    ->channelId(string)
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->status(string)
    ->payload(array)
    ->sync(); // PNDataSyncChannelResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Optional | `server-generated` | Channel identifier. Omit to let the server generate a UUID. Max 255 characters. |
| entityClass | string | Optional | `Channel` | Name of the entity class this channel belongs to. Must be `Channel` or one of its subclasses. Defaults to `Channel` on the server if omitted. Set at creation and immutable afterward. |
| entityClassVersion | int | Yes |  | Version of the channel class schema. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->createChannel()
    ->channelId('channel-summer-sale')
    ->entityClassVersion(1)
    ->payload(['name' => 'Summer Sale', 'type' => 'promotion'])
    ->sync();

printf("Created %s with ETag %s\n", $result->getId(), $result->getETag());
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get channel

Returns a single channel by `channelId`.

#### Method(s)

```php
$pubnub->dataSync()->getChannel()
    ->channelId(string)
    ->sync(); // PNDataSyncChannelResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getChannel()
    ->channelId('channel-summer-sale')
    ->sync();

printf("Fetched %s\n", $result->getId());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T09:05:00.000Z",
        "eTag": "GhIjKlMnOpQrSt"
    }
}
```

### Get all channels

Returns a paginated list of channels. All parameters are optional, so you can call `getChannels` and finish with `sync()` straight away. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```php
$pubnub->dataSync()->getChannels()
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->cursor(string)
    ->limit(int)
    ->filterFast(string)
    ->filter(string)
    ->sort(string|array)
    ->sync(); // PNDataSyncChannelsResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityClass | string | Optional | `all channel classes` | Channel class to list. Omit to list the Global `Channel` class and all of its subclasses. |
| entityClassVersion | int | Optional | `all versions` | Channel class version to list. Omit to list channels across every version of the class. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of channels per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string \| array | Optional |  | Order results. Pass a string of fields each optionally suffixed with `:asc` or `:desc`, or an array that the SDK joins into one. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getChannels()
    ->sync();

printf("Fetched %d channels\n", $result->count());
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "channel-summer-sale",
            "entityClass": "Channel",
            "entityClassVersion": 1,
            "entityClassLevel": "Global",
            "payload": { "name": "Summer Sale", "type": "promotion" },
            "createdAt": "2026-07-13T09:05:00.000Z",
            "updatedAt": "2026-07-13T09:05:00.000Z",
            "eTag": "GhIjKlMnOpQrSt"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getChannels()
    ->filterFast('type == "promotion"')
    ->sync();

printf("Found %d channels\n", $result->count());
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getChannels()
    ->filter('name LIKE "*Summer*"')
    ->sync();

printf("Found %d channels\n", $result->count());
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getPage()->getNextCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getPage()->hasNext()` is `false`.

```php
$cursor = null;

do {
    $request = $pubnub->dataSync()->getChannels()
        ->limit(50);

    if ($cursor !== null) {
        $request->cursor($cursor);
    }

    $result = $request->sync();

    foreach ($result->getData() as $item) {
        printf("%s\n", $item->getId());
    }

    $page = $result->getPage();
    $cursor = $page !== null && $page->hasNext() ? $page->getNextCursor() : null;
} while ($cursor !== null);
```

### Set channel

Replaces a channel in full (PUT). Send the complete set of fields, any field you omit is cleared. `entityClass` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesETag`. For a partial update, use [Update channel](#update-channel).

#### Method(s)

```php
$pubnub->dataSync()->setChannel()
    ->channelId(string)
    ->entityClassVersion(int)
    ->status(string)
    ->payload(array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncChannelResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| entityClassVersion | int | Yes |  | Version of the channel class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->setChannel()
    ->channelId('channel-summer-sale')
    ->entityClassVersion(1)
    ->payload(['name' => 'Summer Sale 2026', 'type' => 'promotion'])
    ->sync();

printf("Replaced channel, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:00:00.000Z",
        "eTag": "IjKlMnOpQrStUv"
    }
}
```

### Update channel

Applies a partial update to a channel with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```php
$pubnub->dataSync()->updateChannel()
    ->channelId(string)
    ->patch(PNDataSyncPatch|array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncChannelResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| patch | PNDataSyncPatch \| array | Yes |  | One or more JSON Patch operations. Must contain at least one item. Pass a `PNDataSyncPatch` builder or a raw array of RFC 6902 operations. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$patch = (new PNDataSyncPatch())
    ->replace('/payload/name', 'Summer Sale 2026');

$result = $pubnub->dataSync()->updateChannel()
    ->channelId('channel-summer-sale')
    ->patch($patch)
    ->sync();

printf("Patched channel, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "channel-summer-sale",
        "status": "active",
        "entityClass": "Channel",
        "entityClassVersion": 1,
        "entityClassLevel": "Global",
        "payload": { "name": "Summer Sale 2026", "type": "promotion" },
        "createdAt": "2026-07-13T09:05:00.000Z",
        "updatedAt": "2026-07-13T11:05:00.000Z",
        "eTag": "KlMnOpQrStUvWx"
    }
}
```

### Remove channel

Deletes a channel by `channelId`.

#### Method(s)

```php
$pubnub->dataSync()->deleteChannel()
    ->channelId(string)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncDeleteResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | string | Yes |  | Channel identifier. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$pubnub->dataSync()->deleteChannel()
    ->channelId('channel-summer-sale')
    ->sync();
```

#### Response

```json
{
    "status": 200
}
```

## Memberships

A membership links a user to a channel and carries its own `payload`. In the running example, Alice is a member of `channel-summer-sale` with the payload `{ "role": "viewer" }`. Refer to [memberships](https://www.pubnub.com/docs/data-storage/structured-data/built-in-types.md#memberships) for the concept.

A membership is a relationship of the built-in Global `Membership` [relationship class](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md), whose two sides are surfaced as `channelId` and `userId`. Every membership response includes both `relationshipClass` and `relationshipClassVersion`. The class is assigned by the service, so the `createMembership` and `setMembership` methods take no class parameter.

Relationship classes [don't support inheritance](https://www.pubnub.com/docs/data-storage/structured-data/schemas.md#relationship-class-inheritance), and only the Global `Membership` class produces memberships, so `relationshipClass` is always `Membership` and `relationshipClassVersion` is the only part that varies.

### Create membership

Creates a membership linking a user to a channel. The `userId`/`channelId` pair must be unique for the membership class. A membership that duplicates an existing pair is rejected with a `409`.

#### Method(s)

```php
$pubnub->dataSync()->createMembership()
    ->membershipId(string)
    ->channelId(string)
    ->userId(string)
    ->relationshipClassVersion(int)
    ->status(string)
    ->payload(array)
    ->sync(); // PNDataSyncMembershipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Optional | `server-generated` | Membership identifier. Omit to let the server generate a UUID. Max 255 characters. |
| channelId | string | Yes |  | Identifier of the channel in the membership. |
| userId | string | Yes |  | Identifier of the user in the membership. |
| relationshipClassVersion | int | Yes |  | Version of the Membership relationship class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->createMembership()
    ->membershipId('membership-alice-summer-sale')
    ->channelId('channel-summer-sale')
    ->userId('user-alice')
    ->relationshipClassVersion(1)
    ->payload(['role' => 'viewer'])
    ->sync();

printf("Created %s with ETag %s\n", $result->getId(), $result->getETag());
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get membership

Returns a single membership by `membershipId`.

#### Method(s)

```php
$pubnub->dataSync()->getMembership()
    ->membershipId(string)
    ->sync(); // PNDataSyncMembershipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getMembership()
    ->membershipId('membership-alice-summer-sale')
    ->sync();

printf("Fetched %s\n", $result->getId());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "viewer" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T09:10:00.000Z",
        "eTag": "MnOpQrStUvWxYz"
    }
}
```

### Get all memberships

Returns a paginated list of memberships. All parameters are optional, so you can call `getMemberships` and finish with `sync()` straight away. `userId` and `channelId` can be set independently, together, or omitted entirely. Filter by `userId` to list a user's memberships or by `channelId` to list a channel's members. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```php
$pubnub->dataSync()->getMemberships()
    ->userId(string)
    ->channelId(string)
    ->relationshipClassVersion(int)
    ->cursor(string)
    ->limit(int)
    ->filterFast(string)
    ->filter(string)
    ->sort(string|array)
    ->sync(); // PNDataSyncMembershipsResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | string | Optional |  | List only memberships for this user. |
| channelId | string | Optional |  | List only memberships for this channel. |
| relationshipClassVersion | int | Optional | `all versions` | Membership class version to list. Omit to list memberships across every version of the class. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of memberships per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string \| array | Optional |  | Order results. Pass a string of fields each optionally suffixed with `:asc` or `:desc`, or an array that the SDK joins into one. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getMemberships()
    ->userId('user-alice')
    ->sync();

printf("Fetched %d memberships\n", $result->count());
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "membership-alice-summer-sale",
            "channelId": "channel-summer-sale",
            "userId": "user-alice",
            "relationshipClass": "Membership",
            "relationshipClassVersion": 1,
            "payload": { "role": "viewer" },
            "createdAt": "2026-07-13T09:10:00.000Z",
            "updatedAt": "2026-07-13T09:10:00.000Z",
            "eTag": "MnOpQrStUvWxYz"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List a channel's members with channelId

Pass `channelId` instead of `userId` to list the members of a channel rather than a user's memberships.

```php
$result = $pubnub->dataSync()->getMemberships()
    ->channelId('channel-summer-sale')
    ->sync();

printf("Found %d members\n", $result->count());
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getMemberships()
    ->userId('user-alice')
    ->filterFast('role == "viewer"')
    ->sync();

printf("Found %d memberships\n", $result->count());
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getMemberships()
    ->userId('user-alice')
    ->filter('role LIKE "*view*"')
    ->sync();

printf("Found %d memberships\n", $result->count());
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getPage()->getNextCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getPage()->hasNext()` is `false`.

```php
$cursor = null;

do {
    $request = $pubnub->dataSync()->getMemberships()
    ->userId('user-alice')
        ->limit(50);

    if ($cursor !== null) {
        $request->cursor($cursor);
    }

    $result = $request->sync();

    foreach ($result->getData() as $item) {
        printf("%s\n", $item->getId());
    }

    $page = $result->getPage();
    $cursor = $page !== null && $page->hasNext() ? $page->getNextCursor() : null;
} while ($cursor !== null);
```

### Set membership

Replaces a membership in full (PUT). Send the complete set of fields, any field you omit is cleared. The linked user and channel ids are immutable, so `setMembership` doesn't expose `userId`/`channelId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesETag`. For a partial update, use [Update membership](#update-membership).

#### Method(s)

```php
$pubnub->dataSync()->setMembership()
    ->membershipId(string)
    ->relationshipClassVersion(int)
    ->status(string)
    ->payload(array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncMembershipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| relationshipClassVersion | int | Yes |  | Version of the Membership relationship class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->setMembership()
    ->membershipId('membership-alice-summer-sale')
    ->relationshipClassVersion(1)
    ->payload(['role' => 'moderator'])
    ->sync();

printf("Replaced membership, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:00:00.000Z",
        "eTag": "OpQrStUvWxYzAb"
    }
}
```

### Update membership

Applies a partial update to a membership with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```php
$pubnub->dataSync()->updateMembership()
    ->membershipId(string)
    ->patch(PNDataSyncPatch|array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncMembershipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| patch | PNDataSyncPatch \| array | Yes |  | One or more JSON Patch operations. Must contain at least one item. Pass a `PNDataSyncPatch` builder or a raw array of RFC 6902 operations. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$patch = (new PNDataSyncPatch())
    ->replace('/payload/role', 'moderator');

$result = $pubnub->dataSync()->updateMembership()
    ->membershipId('membership-alice-summer-sale')
    ->patch($patch)
    ->sync();

printf("Patched membership, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "membership-alice-summer-sale",
        "status": "active",
        "channelId": "channel-summer-sale",
        "userId": "user-alice",
        "relationshipClass": "Membership",
        "relationshipClassVersion": 1,
        "payload": { "role": "moderator" },
        "createdAt": "2026-07-13T09:10:00.000Z",
        "updatedAt": "2026-07-13T12:05:00.000Z",
        "eTag": "QrStUvWxYzAbCd"
    }
}
```

### Remove membership

Deletes a membership by `membershipId`.

#### Method(s)

```php
$pubnub->dataSync()->deleteMembership()
    ->membershipId(string)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncDeleteResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| membershipId | string | Yes |  | Membership identifier. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$pubnub->dataSync()->deleteMembership()
    ->membershipId('membership-alice-summer-sale')
    ->sync();
```

#### Response

```json
{
    "status": 200
}
```

## Entities

Entities are instances of the custom [entity classes](https://www.pubnub.com/docs/admin-api/get-all-entity-class-entries.md) you define on your keyset. In the running example, `product` is a class and `product-sneaker-42` is an instance. Use [Create a new entity class](https://www.pubnub.com/docs/admin-api/create-a-new-entity-class.md) to declare a class, and [Get entity class by ID](https://www.pubnub.com/docs/admin-api/get-entity-class-by-id.md) to read the property, filtering, and projection declarations that govern its instances.

Entity classes can extend one another. Listing a class also returns the entities of its subclasses, so `getEntities()->entityClass('product')` returns every `product` plus every instance of a class that extends `product`.

### Create entity

Creates an entity of a given class and version.

#### Method(s)

```php
$pubnub->dataSync()->createEntity()
    ->entityId(string)
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->status(string)
    ->payload(array)
    ->sync(); // PNDataSyncEntityResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Optional | `server-generated` | Entity identifier. Omit to let the server generate a UUID. Max 255 characters. |
| entityClass | string | Yes |  | Name of the entity class this instance belongs to. Set at creation and immutable afterward. |
| entityClassVersion | int | Yes |  | Version of the entity class schema. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate classes with the same name defined at different levels. Set at creation and immutable afterward. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->createEntity()
    ->entityId('product-sneaker-42')
    ->entityClass('product')
    ->entityClassVersion(1)
    ->payload(['name' => 'Retro Sneaker', 'price' => 89.99, 'stock' => 12])
    ->sync();

printf("Created %s with ETag %s\n", $result->getId(), $result->getETag());
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get entity

Returns a single entity by `entityId`.

#### Method(s)

```php
$pubnub->dataSync()->getEntity()
    ->entityId(string)
    ->sync(); // PNDataSyncEntityResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getEntity()
    ->entityId('product-sneaker-42')
    ->sync();

printf("Fetched %s\n", $result->getId());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T09:15:00.000Z",
        "eTag": "StUvWxYzAbCdEf"
    }
}
```

### Get all entities

Returns a paginated list of entities within a class. The `entityClass` parameter is required, entities are always listed within the context of their class. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```php
$pubnub->dataSync()->getEntities()
    ->entityClass(string)
    ->entityClassVersion(int)
    ->entityClassLevel(string)
    ->cursor(string)
    ->limit(int)
    ->filterFast(string)
    ->filter(string)
    ->sort(string|array)
    ->sync(); // PNDataSyncEntitiesResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityClass | string | Yes |  | Name of the entity class to list. |
| entityClassVersion | int | Optional | `all versions` | Entity class version to list. Omit to list entities across every version of the class. |
| entityClassLevel | string | Optional | `service default` | Class hierarchy level of `entityClass`, either `Global` for a class the service provides or `SubKey` for one defined on your keyset. Used to disambiguate a class name defined at both levels. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of entities per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string \| array | Optional |  | Order results. Pass a string of fields each optionally suffixed with `:asc` or `:desc`, or an array that the SDK joins into one. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getEntities()
    ->entityClass('product')
    ->sync();

printf("Fetched %d entities\n", $result->count());
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "product-sneaker-42",
            "entityClass": "product",
            "entityClassVersion": 1,
            "entityClassLevel": "SubKey",
            "payload": { "name": "Retro Sneaker", "price": 89.99, "stock": 12 },
            "createdAt": "2026-07-13T09:15:00.000Z",
            "updatedAt": "2026-07-13T09:15:00.000Z",
            "eTag": "StUvWxYzAbCdEf"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getEntities()
    ->entityClass('product')
    ->filterFast('price < 100')
    ->sync();

printf("Found %d entities\n", $result->count());
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`, and combine conditions with `&&` and `||`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getEntities()
    ->entityClass('product')
    ->filter('name LIKE "*sneaker*"')
    ->sync();

printf("Found %d entities\n", $result->count());
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getPage()->getNextCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getPage()->hasNext()` is `false`.

```php
$cursor = null;

do {
    $request = $pubnub->dataSync()->getEntities()
    ->entityClass('product')
        ->limit(50);

    if ($cursor !== null) {
        $request->cursor($cursor);
    }

    $result = $request->sync();

    foreach ($result->getData() as $item) {
        printf("%s\n", $item->getId());
    }

    $page = $result->getPage();
    $cursor = $page !== null && $page->hasNext() ? $page->getNextCursor() : null;
} while ($cursor !== null);
```

### Set entity

Replaces an entity in full (PUT). Send the complete set of fields, any field you omit is cleared. `entityClass` is immutable after creation and cannot be sent. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesETag`. For a partial update, use [Update entity](#update-entity).

#### Method(s)

```php
$pubnub->dataSync()->setEntity()
    ->entityId(string)
    ->entityClassVersion(int)
    ->status(string)
    ->payload(array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncEntityResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| entityClassVersion | int | Yes |  | Version of the entity class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->setEntity()
    ->entityId('product-sneaker-42')
    ->entityClassVersion(1)
    ->payload(['name' => 'Retro Sneaker', 'price' => 79.99, 'stock' => 8])
    ->sync();

printf("Replaced entity, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 12 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:00:00.000Z",
        "eTag": "UvWxYzAbCdEfGh"
    }
}
```

### Update entity

Applies a partial update to an entity with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```php
$pubnub->dataSync()->updateEntity()
    ->entityId(string)
    ->patch(PNDataSyncPatch|array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncEntityResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| patch | PNDataSyncPatch \| array | Yes |  | One or more JSON Patch operations. Must contain at least one item. Pass a `PNDataSyncPatch` builder or a raw array of RFC 6902 operations. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$patch = (new PNDataSyncPatch())
    ->replace('/payload/price', 79.99);

$result = $pubnub->dataSync()->updateEntity()
    ->entityId('product-sneaker-42')
    ->patch($patch)
    ->sync();

printf("Patched entity, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "product-sneaker-42",
        "entityClass": "product",
        "entityClassVersion": 1,
        "entityClassLevel": "SubKey",
        "payload": { "name": "Retro Sneaker", "price": 79.99, "stock": 8 },
        "createdAt": "2026-07-13T09:15:00.000Z",
        "updatedAt": "2026-07-13T13:05:00.000Z",
        "eTag": "WxYzAbCdEfGhIj"
    }
}
```

#### Other examples

##### Combine patch operations, and guard the write with ifMatchesETag

A single `updateEntity` call can mix `add`, `replace`, `remove`, `move`, `copy`, and `test` in one `PNDataSyncPatch`. All operations in the call apply together or not at all. Add `ifMatchesETag` (the `ETag` from a prior read) to reject the patch with a `412` if the entity changed since you read it, instead of silently overwriting a concurrent change.

```php
$entity = $pubnub->dataSync()->getEntity()
    ->entityId('product-sneaker-42')
    ->sync();

$patch = (new PNDataSyncPatch())
    ->test('/status', 'active')
    ->add('/payload/tags', ['sale'])
    ->replace('/payload/price', 79.99)
    ->remove('/payload/tempFlag')
    ->move('/payload/oldTag', '/payload/tag')
    ->copy('/payload/price', '/payload/msrp');

$result = $pubnub->dataSync()->updateEntity()
    ->entityId('product-sneaker-42')
    ->ifMatchesETag($entity->getETag())
    ->patch($patch)
    ->sync();

printf("Patched, new ETag %s\n", $result->getETag());
```

### Remove entity

Deletes an entity by `entityId`.

#### Method(s)

```php
$pubnub->dataSync()->deleteEntity()
    ->entityId(string)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncDeleteResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| entityId | string | Yes |  | Entity identifier. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$pubnub->dataSync()->deleteEntity()
    ->entityId('product-sneaker-42')
    ->sync();
```

#### Response

```json
{
    "status": 200
}
```

## Relationships

A relationship links two entities and carries its own `payload`. In the running example, the `ProductOwner` relationship links `seller-bob` to `product-sneaker-42`.

Relationships are instances of the [relationship classes](https://www.pubnub.com/docs/admin-api/get-all-relationship-classes.md) you define on your keyset. A relationship class declares the cardinality the service enforces (`one-to-one`, `one-to-many`, or `many-to-many`) and, optionally, which entity class each side must belong to. Use [Create a new relationship class](https://www.pubnub.com/docs/admin-api/create-a-new-relationship-class.md) to declare a class, and [Get relationship class by name and version](https://www.pubnub.com/docs/admin-api/get-relationship-class-by-name-and-version.md) to read it back.

### Create relationship

Creates a relationship between two entities. The relationship class's cardinality (one-to-one, one-to-many, or many-to-many) is enforced on create. A relationship that violates its class's cardinality is rejected with a `409`.

#### Method(s)

```php
$pubnub->dataSync()->createRelationship()
    ->relationshipId(string)
    ->entityAId(string)
    ->entityBId(string)
    ->relationshipClass(string)
    ->relationshipClassVersion(int)
    ->status(string)
    ->payload(array)
    ->sync(); // PNDataSyncRelationshipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Optional | `server-generated` | Relationship identifier. Omit to let the server generate a UUID. Max 255 characters. |
| entityAId | string | Yes |  | Identifier of the first linked entity. Immutable after creation. |
| entityBId | string | Yes |  | Identifier of the second linked entity. Immutable after creation. |
| relationshipClass | string | Yes |  | Name of the relationship class this instance belongs to. Set at creation and immutable afterward. |
| relationshipClassVersion | int | Yes |  | Version of the relationship class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->createRelationship()
    ->relationshipId('rel-bob-owns-sneaker-42')
    ->entityAId('seller-bob')
    ->entityBId('product-sneaker-42')
    ->relationshipClass('ProductOwner')
    ->relationshipClassVersion(1)
    ->payload(['since' => '2026-07-13'])
    ->sync();

printf("Created %s with ETag %s\n", $result->getId(), $result->getETag());
```

#### Response

```json
{
    "status": 201,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get relationship

Returns a single relationship by `relationshipId`.

#### Method(s)

```php
$pubnub->dataSync()->getRelationship()
    ->relationshipId(string)
    ->sync(); // PNDataSyncRelationshipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getRelationship()
    ->relationshipId('rel-bob-owns-sneaker-42')
    ->sync();

printf("Fetched %s\n", $result->getId());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T09:20:00.000Z",
        "eTag": "YzAbCdEfGhIjKl"
    }
}
```

### Get all relationships

Returns a paginated list of relationships within a class. The `relationshipClass` parameter is required. Filter by `entityAId` or `entityBId` to list a specific entity's links. For pagination, filtering, and sorting, refer to [sorting and pagination](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#sorting-and-pagination).

#### Method(s)

```php
$pubnub->dataSync()->getRelationships()
    ->relationshipClass(string)
    ->relationshipClassVersion(int)
    ->entityAId(string)
    ->entityBId(string)
    ->cursor(string)
    ->limit(int)
    ->filterFast(string)
    ->filter(string)
    ->sort(string|array)
    ->sync(); // PNDataSyncRelationshipsResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipClass | string | Yes |  | Name of the relationship class to list. |
| relationshipClassVersion | int | Optional | `all versions` | Relationship class version to list. Omit to list relationships across every version of the class. |
| entityAId | string | Optional |  | List only relationships whose first entity is this id. |
| entityBId | string | Optional |  | List only relationships whose second entity is this id. |
| cursor | string | Optional |  | Opaque pagination cursor. Omit for the first page. |
| limit | int | Optional | `20` | Maximum number of relationships per page. Max `100`. |
| filterFast | string | Optional |  | Filter expression evaluated against strongly consistent storage, so it reflects the latest writes. Accepts up to 10 conditions by default (raisable per keyset), over properties declared with filtering mode `simple` or `full`. Cannot be combined with `filter`. |
| filter | string | Optional |  | Filter expression evaluated against eventually consistent storage, so results can briefly lag writes. Supports the full expression language, over properties declared with filtering mode `full`. Cannot be combined with `filterFast`. |
| sort | string \| array | Optional |  | Order results. Pass a string of fields each optionally suffixed with `:asc` or `:desc`, or an array that the SDK joins into one. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->getRelationships()
    ->relationshipClass('ProductOwner')
    ->sync();

printf("Fetched %d relationships\n", $result->count());
```

#### Response

```json
{
    "status": 200,
    "data": [
        {
            "id": "rel-bob-owns-sneaker-42",
            "entityAId": "seller-bob",
            "entityBId": "product-sneaker-42",
            "relationshipClass": "ProductOwner",
            "relationshipClassVersion": 1,
            "payload": { "since": "2026-07-13" },
            "createdAt": "2026-07-13T09:20:00.000Z",
            "updatedAt": "2026-07-13T09:20:00.000Z",
            "eTag": "YzAbCdEfGhIjKl"
        }
    ],
    "meta": {
        "next_cursor": null,
        "has_next": false,
        "limit": 20
    }
}
```

#### Other examples

##### List an entity's incoming links with entityBId

Pass `entityBId` instead of `entityAId` to list relationships where the entity is on the second side of the link.

```php
$result = $pubnub->dataSync()->getRelationships()
    ->relationshipClass('ProductOwner')
    ->entityBId('product-sneaker-42')
    ->sync();

printf("Found %d relationships\n", $result->count());
```

##### Filter with filterFast

`filterFast` is evaluated against strongly consistent storage, so it matches an object you just wrote. It runs over properties declared with filtering mode `simple` or `full` and accepts up to 10 conditions by default (raisable per keyset). Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filter`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getRelationships()
    ->relationshipClass('ProductOwner')
    ->filterFast('since >= "2026-01-01"')
    ->sync();

printf("Found %d relationships\n", $result->count());
```

##### Filter with filter

`filter` runs over properties declared with filtering mode `full` and is evaluated against eventually consistent storage, so a very recent write may not be matched yet. Reference a declared property by its `name`, not its `path`. It shares the same expression language as `filterFast`, so only one of the two can be sent per call.

```php
$result = $pubnub->dataSync()->getRelationships()
    ->relationshipClass('ProductOwner')
    ->filter('since LIKE "2026*"')
    ->sync();

printf("Found %d relationships\n", $result->count());
```

##### Page through results with cursor

Pass no `cursor` on the first call. Take `getPage()->getNextCursor()` from the result and pass it back as `cursor` on the next call. Stop when `getPage()->hasNext()` is `false`.

```php
$cursor = null;

do {
    $request = $pubnub->dataSync()->getRelationships()
    ->relationshipClass('ProductOwner')
        ->limit(50);

    if ($cursor !== null) {
        $request->cursor($cursor);
    }

    $result = $request->sync();

    foreach ($result->getData() as $item) {
        printf("%s\n", $item->getId());
    }

    $page = $result->getPage();
    $cursor = $page !== null && $page->hasNext() ? $page->getNextCursor() : null;
} while ($cursor !== null);
```

### Set relationship

Replaces a relationship in full (PUT). Send the complete set of fields, any field you omit is cleared. `relationshipClass` is immutable after creation and cannot be sent, and the linked entity ids are immutable too, so `setRelationship` doesn't expose `entityAId`/`entityBId` at all, there's nothing to resend. Refer to [optimistic concurrency with ETags](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#optimistic-concurrency-with-etags) for `ifMatchesETag`. For a partial update, use [Update relationship](#update-relationship).

#### Method(s)

```php
$pubnub->dataSync()->setRelationship()
    ->relationshipId(string)
    ->relationshipClassVersion(int)
    ->status(string)
    ->payload(array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncRelationshipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| relationshipClassVersion | int | Yes |  | Version of the relationship class schema. |
| status | string | Optional |  | Free-form lifecycle status. Max 100 characters. |
| payload | array | Optional |  | Free-form JSON object holding your application data. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The update succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$result = $pubnub->dataSync()->setRelationship()
    ->relationshipId('rel-bob-owns-sneaker-42')
    ->relationshipClassVersion(1)
    ->payload(['since' => '2026-07-13', 'tier' => 'gold'])
    ->sync();

printf("Replaced relationship, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "gold" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:00:00.000Z",
        "eTag": "AbCdEfGhIjKlMn"
    }
}
```

### Update relationship

Applies a partial update to a relationship with raw JSON Patch operations. Refer to [partial update](https://www.pubnub.com/docs/data-storage/structured-data/data-operations.md#partial-update) for the operation model.

#### Method(s)

```php
$pubnub->dataSync()->updateRelationship()
    ->relationshipId(string)
    ->patch(PNDataSyncPatch|array)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncRelationshipResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| patch | PNDataSyncPatch \| array | Yes |  | One or more JSON Patch operations. Must contain at least one item. Pass a `PNDataSyncPatch` builder or a raw array of RFC 6902 operations. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The patch succeeds only if it still matches, otherwise the server returns `412`. |

Use a JSON Pointer that starts with `/payload/` to target payload fields, or a root pointer (for example `/status`) to target a top-level field.

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$patch = (new PNDataSyncPatch())
    ->replace('/payload/tier', 'platinum');

$result = $pubnub->dataSync()->updateRelationship()
    ->relationshipId('rel-bob-owns-sneaker-42')
    ->patch($patch)
    ->sync();

printf("Patched relationship, new ETag %s\n", $result->getETag());
```

#### Response

```json
{
    "status": 200,
    "data": {
        "id": "rel-bob-owns-sneaker-42",
        "entityAId": "seller-bob",
        "entityBId": "product-sneaker-42",
        "relationshipClass": "ProductOwner",
        "relationshipClassVersion": 1,
        "payload": { "since": "2026-07-13", "tier": "platinum" },
        "createdAt": "2026-07-13T09:20:00.000Z",
        "updatedAt": "2026-07-13T14:05:00.000Z",
        "eTag": "CdEfGhIjKlMnOp"
    }
}
```

### Remove relationship

Deletes a relationship by `relationshipId`.

#### Method(s)

```php
$pubnub->dataSync()->deleteRelationship()
    ->relationshipId(string)
    ->ifMatchesETag(string)
    ->sync(); // PNDataSyncDeleteResult
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| relationshipId | string | Yes |  | Relationship identifier. |
| ifMatchesETag | string | Optional |  | The `ETag` from a prior read. The delete succeeds only if it still matches, otherwise the server returns `412`. |

#### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```php
$publishKey = getenv('PUBLISH_KEY') ?: 'demo';
$subscribeKey = getenv('SUBSCRIBE_KEY') ?: 'demo';
$secretKey = getenv('SECRET_KEY') ?: 'demo';

$config = new PNConfiguration();
$config->setSubscribeKey($subscribeKey);
$config->setPublishKey($publishKey);
$config->setSecretKey($secretKey);
$config->setUserId('php-datasync-sample');

$pubnub = new PubNub($config);
$pubnub->dataSync()->deleteRelationship()
    ->relationshipId('rel-bob-owns-sneaker-42')
    ->sync();
```

#### Response

```json
{
    "status": 200
}
```

## Real-time updates

DataSync objects can publish `create`, `update`, and `delete` events that you receive in real time by subclassing `SubscribeCallback` and overriding `dataSyncEvent`. Attach the listener to the PubNub client with `addListener`, then subscribe to the object's data channel with `subscribe()->channels(...)->execute()`, as described in [Add DataSync listener](https://www.pubnub.com/docs/sdks/php/api-reference/publish-and-subscribe.md#add-datasync-listener).

```php
class DataSyncListener extends SubscribeCallback
{
    public function status($pubnub, $status)
    {
    }

    public function message($pubnub, $message)
    {
    }

    public function presence($pubnub, $presence)
    {
    }

    public function dataSyncEvent($pubnub, $event)
    {
        printf(
            "%s %s %s (class %s)\n",
            $event->getEvent(),
            $event->getType(),
            $event->getId(),
            $event->getClassName()
        );
    }
}

$pubnub->addListener(new DataSyncListener());
$pubnub->subscribe()->channels('product-sneaker-42')->execute();
```

Each event names the change in `getEvent()`, identifies the object kind in `getType()` (`user`, `channel`, `membership`, `entity`, or `relationship`), and carries the object state in `getEntity()`, `getRelationship()`, or `getMembership()`. For a `delete` event, `getId()` and `getDeletedAt()` carry the identifier and the deletion timestamp, and the three state getters return `null`.

`getType()` names the object kind directly, while create and update events populate one of the typed getters:

| Change to | `getType()` | State arrives in |
| --- | --- | --- |
| A user | `user` | `getEntity()` |
| A channel | `channel` | `getEntity()` |
| An entity | `entity` | `getEntity()` |
| A membership | `membership` | `getMembership()` and `getRelationship()` |
| A relationship | `relationship` | `getRelationship()` |

Dispatch on `getType()` rather than on which getter returns a record, because `getEntity()` is shared by three kinds. `getClassName()` tells you the specific class within a kind, for example which subclass of `User` an event belongs to.

### Where each event is delivered

The channels that receive an event depend on the changed object. A relationship or membership never publishes on a channel named after its own id:

| Change to | On `create` | On `update` or `delete` |
| --- | --- | --- |
| A user | The user's `getId()` | The user's `getId()`, plus the `getId()` of every entity, user, or channel connected to it by a relationship or membership |
| A channel | The channel's `getId()` | The channel's `getId()`, plus the `getId()` of every entity, user, or channel connected to it by a relationship or membership |
| An entity | The entity's `getId()` | The entity's `getId()`, plus the `getId()` of every entity, user, or channel connected to it by a relationship or membership |
| A membership | **Both** the `getUserId()` and the `getChannelId()` of the membership | Same as `create` |
| A relationship | **Both** the `getEntityAId()` and the `getEntityBId()` of the relationship | Same as `create` |

:::note Update and delete also fan out to connected objects
An update or delete on a user, channel, or entity is also delivered on the `getId()` channel of every other object connected to it by a relationship or membership, in either direction, at the time of the change. A client subscribed to a connected object's channel receives the event too, even though that object itself did not change. A create does not fan out this way, because nothing can be connected to a brand new object yet.
The connected channels are entity, user, and channel ids. Relationships and memberships never get an id channel of their own, so they never appear in this fan-out as a channel name.
:::

So to see memberships appear and disappear for Alice, subscribe to `user-alice` rather than the membership id. A client subscribed to both sides of the same link receives the change twice, once per channel. Deduplicate create and update events on the object's `getId()` and `getUpdatedAt()`, and delete events on `getId()` and `getDeletedAt()`.

For a membership event, `getRelationship()->getEntityAId()` is the channel id and `getRelationship()->getEntityBId()` is the user id. The service sends these as `channelId` and `userId`, and the SDK maps them onto the A and B sides so that one result type serves both memberships and your own relationships. `getMembership()` returns the same record under its own names.

### Projection channels

Each [projection](https://www.pubnub.com/docs/sdks/php/api-reference/access-manager.md#grant-token) declared on the class gets its own event, published to its own channel, and carrying only that projection's view of the payload:

| Projection | Channel | Payload |
| --- | --- | --- |
| `__default__` (the base projection) | The object's own id, for example `product-sneaker-42` | The fields tagged `__default__` |
| Any named projection, for example `admin` | `__<projection>__<id>`, for example `__admin__product-sneaker-42` | The fields tagged with that projection |

A projection name must start with a letter or digit, so a leading `__` marks a projection channel, with `__default__` as the only exception.

:::warning Avoid ids that start with two underscores
A projection channel is named `__<projection>__<id>`, so an object id in that form can collide with another object's projection channel. The service doesn't reject such ids today, so avoid any id that starts with `__`.
:::

Filtering applies to `getPayload()` and to `getStatus()`: each is included in a given projection's event only if the class declares it under that projection, falling back to `__default__` when the class never declares `status`. `getId()`, `getETag()`, `getCreatedAt()`, `getUpdatedAt()`, and `getExpiresAt()` are never filtered. Every projection's event carries them unchanged.

So one change to an object whose class declares an `admin` projection publishes two events, and a client subscribed only to `product-sneaker-42` never sees the `admin`-only fields:

```php
class ProjectionListener extends SubscribeCallback
{
    public function status($pubnub, $status)
    {
    }

    public function message($pubnub, $message)
    {
    }

    public function presence($pubnub, $presence)
    {
    }

    public function dataSyncEvent($pubnub, $event)
    {
        printf(
            "%s %s %s (class %s)\n",
            $event->getEvent(),
            $event->getType(),
            $event->getId(),
            $event->getClassName()
        );
    }
}

$pubnub->addListener(new ProjectionListener());
$pubnub->subscribe()
    ->channels(['product-sneaker-42', '__admin__product-sneaker-42'])
    ->execute();
```

If the class declares no properties at all there is nothing to filter, so a single unfiltered event is published to the object's own id channel.

:::warning Projection channels need channel grants
Publishing to `__<projection>__<id>` is an ordinary channel publish, and it isn't gated by the `dataSyncProjections` entries in a token. Use Access Manager `addChannelResources` grants to control who can subscribe to a projection channel. Anyone who can subscribe there receives the restricted fields. Refer to [Grant token](https://www.pubnub.com/docs/sdks/php/api-reference/access-manager.md#grant-token).
:::

Delete events are never filtered by a projection.

Events are off by default and are enabled per class in the [Admin Portal](https://admin.pubnub.com). Refer to [enabling events](https://www.pubnub.com/docs/data-storage/structured-data/events.md#enable-datasync-events) for how to turn them on, and [receiving events](https://www.pubnub.com/docs/data-storage/structured-data/events.md) for the listener flow.

Last updated at: 2026-10-05T14:28:43.000Z
