# ServiceConnection

> Opens a service-account connection only after requiring and establishing verified StartTLS.

[API reference](/docs/api/index.md) › [LDAP](/docs/extensions/ldap/reference/index.md) › ServiceConnection

| final class | `yii2\extensions\ldap\ServiceConnection` |
| --- | --- |
| Extends | `LdapRecord\Connection` |
| Source | [`src/ServiceConnection.php`](https://github.com/yii2-extensions/ldap/blob/main/src/ServiceConnection.php#L28) |

Opens a service-account connection only after requiring and establishing verified StartTLS.

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`auth()`](#method-auth) | Creates a guard without sending service credentials to global authentication event listeners. | `ServiceConnection` |
| [`connect()`](#method-connect) | Establishes a bound session or fails outside the native query retry handler. | `ServiceConnection` |
| [`initialize()`](#method-initialize) | Sets options on the specific LDAP handle, not on the process-wide defaults. | `ServiceConnection` |
| [`query()`](#method-query) | Creates the native query builder with strict paged-result handling. | `ServiceConnection` |

## Method details

### auth() <span id="method-auth"></span>

```php
public function auth(): LdapRecord\Auth\Guard
```

Creates a guard without sending service credentials to global authentication event listeners.

**Returns**

`LdapRecord\Auth\Guard`: Authentication guard for this connection.

**Throws**

- [`DirectoryUnavailableException`](/docs/extensions/ldap/reference/directoryunavailableexception/index.md): if the connection cannot establish verified StartTLS.

### connect() <span id="method-connect"></span>

```php
public function connect(string|null $username = null, string|null $password = null): void
```

Establishes a bound session or fails outside the native query retry handler.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$username` | `string\|null` | Explicit bind name. When both arguments are null, uses the configured account. |
| `$password` | `string\|null` | Password corresponding to the explicit bind name. |

**Throws**

- [`DirectoryUnavailableException`](/docs/extensions/ldap/reference/directoryunavailableexception/index.md): if the service account could not bind.

### initialize() <span id="method-initialize"></span>

```php
public function initialize(): void
```

Sets options on the specific LDAP handle, not on the process-wide defaults.

**Throws**

- [`DirectoryUnavailableException`](/docs/extensions/ldap/reference/directoryunavailableexception/index.md): if StartTLS or a required option fails.

### query() <span id="method-query"></span>

```php
public function query(): LdapRecord\Query\Builder
```

Creates the native query builder with strict paged-result handling.

**Returns**

`LdapRecord\Query\Builder`: Query builder configured with this connection's base DN and cache.