# Core classes

Reference for the Surreal class, the ConnectionController, and the supporting connection types in version 2 of the PHP SDK.

The `Surreal` class is the entry point for version 2 of the SDK. It manages the connection, the session, authentication, and query execution.

**Namespace:** `SurrealDB\SDK\Surreal`

**Source:** [src/Surreal.php](https://github.com/surrealdb/surrealdb.php/blob/main/src/Surreal.php)

## Constructor

```php title="Syntax"
new Surreal(?DriverOptions $options = null)
```

`DriverOptions` customises driver-wide behaviour such as the codec, HTTP client, scheduler, and middleware. Pass `null` for the defaults.

```php
use SurrealDB\SDK\Surreal;

$db = new Surreal();
```

## Connection methods

### `connect()` {#connect}

Connect to a SurrealDB endpoint.

```php title="Syntax"
$db->connect(string|Endpoint $url, ?ConnectOptions $options = null): void
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>url</code> <label label="required" /></td>
            <td><code>string | Endpoint</code></td>
            <td>The endpoint to connect to, such as <code>ws://127.0.0.1:8000/rpc</code>.</td>
        </tr>
        <tr>
            <td><code>options</code> <label label="optional" /></td>
            <td><code><a href="#connectoptions">ConnectOptions</a></code></td>
            <td>Namespace, database, authentication, and reconnection settings.</td>
        </tr>
    </tbody>
</table>

```php
$db->connect('ws://127.0.0.1:8000/rpc', new ConnectOptions(
    namespace: 'surrealdb',
    database: 'docs',
));
```

### `close()` {#close}

Close the connection and release its resources.

```php title="Syntax"
$db->close(): void
```

### `status()` {#status}

Return the current [`ConnectionStatus`](#connectionstatus).

```php title="Syntax"
$db->status(): ConnectionStatus
```

### `isConnected()` {#isconnected}

Return whether the connection is established. Equivalent to `status() === ConnectionStatus::Connected`.

```php title="Syntax"
$db->isConnected(): bool
```

### `health()` {#health}

Throw if the instance is unreachable, otherwise return nothing.

```php title="Syntax"
$db->health(): void
```

### `version()` {#version}

Return the server version string, for example `surrealdb-2.1.0`.

```php title="Syntax"
$db->version(): string
```

### `isFeatureSupported()` {#isfeaturesupported}

Return whether a feature is available on the current connection and server.

```php title="Syntax"
$db->isFeatureSupported(Feature $feature): bool
```

### `subscribe()` {#subscribe}

Subscribe to a lifecycle event: `connecting`, `connected`, `reconnecting`, `disconnected`, `error`, `auth`, or `using`. Returns a closure that removes the listener.

```php title="Syntax"
$db->subscribe(string $event, callable $listener): Closure
```

### `connection()` {#connection}

Return the underlying [`ConnectionController`](#connectioncontroller) for advanced operations such as transactions, sessions, and import/export.

```php title="Syntax"
$db->connection(): ConnectionController
```

## Session methods

### `use()` {#use}

Select a namespace and an optional database.

```php title="Syntax"
$db->use(?string $namespace, ?string $database = null): void
```

### `let()` {#let}

Define a session parameter, available in later queries as `$name`.

```php title="Syntax"
$db->let(string $name, mixed $value): void
```

### `unset()` {#unset}

Remove a session parameter.

```php title="Syntax"
$db->unset(string $name): void
```

## Authentication methods

### `signin()` {#signin}

Sign in with a [credential object](/docs/reference/php/v2/concepts/authentication.md#credential-types) or an array. Returns a [`Tokens`](#tokens) object.

```php title="Syntax"
$db->signin(Credentials|array $auth): Tokens
```

### `signup()` {#signup}

Sign up a new record user. Returns a [`Tokens`](#tokens) object.

```php title="Syntax"
$db->signup(Credentials|array $auth): Tokens
```

### `authenticate()` {#authenticate}

Authenticate the session with an existing token.

```php title="Syntax"
$db->authenticate(Token|string $token): void
```

### `invalidate()` {#invalidate}

Clear the session's authentication.

```php title="Syntax"
$db->invalidate(): void
```

## Query methods

### `query()` {#query}

Execute a [`BoundQuery`](/docs/reference/php/v2/api/utilities.md#boundquery), returning one result per statement.

```php title="Syntax"
$db->query(BoundQuery $query): array
```

### `run()` {#run}

Execute raw SurrealQL with optional bindings, returning one result per statement.

```php title="Syntax"
$db->run(string $surql, array $bindings = []): array
```

### Statement builders

These methods start a fluent [query builder](/docs/reference/php/v2/api/query-builders.md). Call `execute()` to run it.

- `select($what)`, `create($what)`, `update($what)`, `upsert($what)`, `delete($what)`
- `insert($tableOrData, $data = null)`, `relate($from, $edge, $to, $data = null)`
- `call($name, $version = null, $args = [])`, `auth()`

### `live()` {#live}

Subscribe to a live query by its ID. Returns an iterable of [`LiveMessage`](#livemessage) objects.

```php title="Syntax"
$db->live(string $queryUuid): iterable
```

Iterating the result blocks the process while it waits for messages. See [running without blocking the application](/docs/reference/php/v2/concepts/live-queries.md#running-without-blocking-the-application) for consuming live queries in a worker.

---

## Supporting types

## `ConnectOptions` {#connectoptions}

Per-connection settings passed to `connect()`.

**Namespace:** `SurrealDB\SDK\Connection\ConnectOptions`

```php title="Constructor"
new ConnectOptions(
    ?string $namespace = null,
    ?string $database = null,
    Credentials|Token|AuthProviderInterface|Closure|string|null $authentication = null,
    bool $versionCheck = true,
    bool $invalidateOnExpiry = false,
    bool|array|ReconnectStrategyInterface $reconnect = true,
)
```

## `ConnectionStatus` {#connectionstatus}

A string-backed enum with the connection lifecycle states.

**Namespace:** `SurrealDB\SDK\Connection\ConnectionStatus`

**Values:** `Disconnected`, `Connecting`, `Reconnecting`, `Connected`

## `Tokens` {#tokens}

The result of `signin()` and `signup()`: an access token and an optional refresh token.

**Namespace:** `SurrealDB\SDK\Auth\Tokens`

```php title="Properties"
$tokens->access;   // ?string
$tokens->refresh;  // ?string
```

## `LiveMessage` {#livemessage}

A single live query notification.

**Namespace:** `SurrealDB\SDK\Live\LiveMessage`

```php title="Properties"
$message->queryId;  // string
$message->action;   // LiveAction (Create, Update, Delete, Killed)
$message->record;   // mixed: the affected record id
$message->value;    // mixed: the new record value
```

---

## `ConnectionController` {#connectioncontroller}

The controller orchestrates the connection. Access it with `$db->connection()` for operations that are not on the `Surreal` facade.

**Namespace:** `SurrealDB\SDK\Connection\ConnectionController`

## Transactions

```php title="Syntax"
$db->connection()->begin(?string $session = null): string
$db->connection()->commit(string $txn, ?string $session = null): void
$db->connection()->cancel(string $txn, ?string $session = null): void
```

## Import and export

```php title="Syntax"
$db->connection()->importSql(string $data): void
$db->connection()->exportSql(array $options = []): string
```

```php
$sql = $db->connection()->exportSql();
$db->connection()->importSql($sql);
```

## Token renewal

```php title="Syntax"
$db->connection()->refresh(Tokens $tokens, ?string $session = null): Tokens
$db->connection()->revoke(Tokens $tokens, ?string $session = null): void
```

## Sessions

```php title="Syntax"
$db->connection()->sessions(): array
$db->connection()->createSession(?string $clone = null): string
$db->connection()->destroySession(?string $session): void
```

## See also

- [Query Builders](/docs/reference/php/v2/api/query-builders.md) for the fluent statement API
- [Data types](/docs/reference/php/v2/api/data-types.md) for the value classes
- [Utilities](/docs/reference/php/v2/api/utilities.md) for `BoundQuery`, enums, and driver options
- [Connecting to SurrealDB](/docs/reference/php/v2/concepts/connecting-to-surrealdb.md) for the connection guide
