PHPackages                             google/cloud-spanner - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. google/cloud-spanner

ActiveLibrary[Database &amp; ORM](/categories/database)

google/cloud-spanner
====================

Cloud Spanner Client for PHP

v2.10.0(2w ago)21601.3k↑24.9%96Apache-2.0PHPPHP ^8.1CI passing

Since May 18Pushed 2w ago48 watchersCompare

[ Source](https://github.com/googleapis/google-cloud-php-spanner)[ Packagist](https://packagist.org/packages/google/cloud-spanner)[ RSS](/packages/google-cloud-spanner/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (10)Dependencies (50)Versions (202)Used By (6)

Google Cloud Spanner for PHP
============================

[](#google-cloud-spanner-for-php)

> Idiomatic PHP client for [Cloud Spanner](https://cloud.google.com/spanner/).

[![Latest Stable Version](https://camo.githubusercontent.com/854af96d349cbd36f101f820e2335ed929c7edf2a30b8bc063471a2dd94c11b7/68747470733a2f2f706f7365722e707567782e6f72672f676f6f676c652f636c6f75642d7370616e6e65722f762f737461626c65)](https://packagist.org/packages/google/cloud-spanner) [![Packagist](https://camo.githubusercontent.com/3eaf114bae2fb6c30fa5fe4f920d4b30ba8828d80c2bd5735c4ce779cd093cde/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f676f6f676c652f636c6f75642d7370616e6e65722e737667)](https://packagist.org/packages/google/cloud-spanner)

- [API documentation](https://cloud.google.com/php/docs/reference/cloud-spanner/latest)

**NOTE:** This repository is part of [Google Cloud PHP](https://github.com/googleapis/google-cloud-php). Any support requests, bug reports, or development contributions should be directed to that project.

A fully managed, mission-critical, relational database service that offers transactional consistency at global scale, schemas, SQL (ANSI 2011 with extensions), and automatic, synchronous replication for high availability.

### Installation

[](#installation)

To begin, install the preferred dependency manager for PHP, [Composer](https://getcomposer.org/).

Now install this component:

```
$ composer require google/cloud-spanner
```

This component requires the gRPC extension. Please see our [gRPC installation guide](https://cloud.google.com/php/grpc)for more information on how to configure the extension.

### Authentication

[](#authentication)

Please see our [Authentication guide](https://github.com/googleapis/google-cloud-php/blob/main/AUTHENTICATION.md) for more information on authenticating your client. Once authenticated, you'll be ready to start making requests.

### Sample

[](#sample)

```
use Google\Cloud\Spanner\SpannerClient;

// Create a client.
$spannerClient = new SpannerClient();

$db = $spanner->connect('my-instance', 'my-database');

$userQuery = $db->execute('SELECT * FROM Users WHERE id = @id', [
    'parameters' => [
        'id' => $userId
    ]
]);

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['firstName'];
```

### Multiplexed Sessions

[](#multiplexed-sessions)

The V2 version of the Spanner Client Library for PHP uses [Multiplexed Sessions](https://cloud.google.com/spanner/docs/sessions#multiplexed_sessions). Multiplexed Sessions allow your application to create a large number of concurrent requests on a single session. Some advantages include reduced backend resource consumption due to a more straightforward session management protocol, and less management as sessions no longer require cleanup after use or keep-alive requests when idle.

#### Session Caching

[](#session-caching)

The session cache is configured with a default cache which uses the PSR-6 compatible [`SysvCacheItemPool`](https://github.com/googleapis/google-auth-library-php/blob/main/src/Cache/SysVCacheItemPool.php)when the [`sysvshm`](https://www.php.net/manual/en/book.sem.php) extension is enabled, and [`FileSystemCacheItemPool`](https://github.com/googleapis/google-auth-library-php/blob/main/src/Cache/FileSystemCacheItemPool.php) when `sysvshm` is not available. This ensures that your processes share a single multiplex session for each database and creator role.

To change the default cache pool, use the option `cacheItemPool` when instantiating your Spanner client:

```
use Google\Cloud\Spanner\SpannerClient;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
// available by running `composer install symfony/cache`
$fileCacheItemPool = new FilesystemAdapter();
// configure through SpannerClient constructor
$spanner = new SpannerClient(['cacheItemPool' => $fileCacheItemPool]);
$database = $spanner->instance($instanceId)->database($databaseId);
```

This can also be passed in as an option to the `instance` or `database` methods:

```
$spanner = new SpannerClient();
// configure through instance method
$database = $spanner
    ->instance($instanceId, ['cacheItemPool' => $fileCacheItemPool])
    ->database($databaseId);
// configure through database method
$database = $spanner
    ->instance($instanceId)
    ->database($databaseId, ['cacheItemPool' => $fileCacheItemPool]);
```

#### Refreshing Sessions

[](#refreshing-sessions)

Sessions will refresh synchronously every 7 days. You can use this script to refresh the session asynchronously, in to avoid latency in your application (recommended every ~24 hours):

```
// If you are using a custom PSR-6 cache via the "cacheItemPool" client option in your
// application, you will need to supply a cache with the same configuration here in
// order to properly refresh the session.
$spanner = new SpannerClient();

$sessionCache = $spanner
    ->instance($instanceId)
    ->database($databaseId)
    ->session();

// this will force-refresh the session
$sessionCache->refresh();
```

#### Session Locking

[](#session-locking)

Locking occurs when a new session is created, and ensures no race conditions occur when a session expires. Locking uses a [`Semaphore`](https://github.com/googleapis/google-cloud-php/blob/main/Core/src/Lock/SemaphoreLock.php) lock when `sysvmsg`, `sysvsem`, and `sysvshm` extensions are enabled, and a [`Flock`](https://github.com/googleapis/google-cloud-php/blob/main/Core/src/Lock/FlockLock.php) lock otherwise. To configure a custom lock, supply a class implementing [`LockInterface`](https://github.com/googleapis/google-cloud-php/blob/main/Core/src/Lock/LockInterface.php) when calling `Instance::database`. Here's an example which encorporates the [Symfony Lock component](https://symfony.com/doc/current/components/lock.html):

```
use Google\Cloud\Core\Lock\LockInterface;
use Google\Cloud\Spanner\SpannerClient;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\SharedLockInterface;
use Symfony\Component\Lock\Store\SemaphoreStore;

// Available by running `composer install symfony/lock`
$store = new SemaphoreStore();
$factory = new LockFactory($store);

// Create an adapter for Symfony's SharedLockInterface and Google's LockInterface
$lock = new class ($factory->createLock($databaseId)) implements LockInterface {
    public function __construct(private SharedLockInterface $lock) {
    }

    public function acquire(array $options = []) {
        return $this->lock->acquire()
    }

    public function release() {
        return $this->lock->acquire()
    }

    public function synchronize(callable $func, array $options = []) {
        if ($this->lock->acquire($options['blocking'] ?? true)) {
            return $func();
        }
    }
}

// Configure our custom lock on our database using the "lock" option
$spanner = new SpannerClient();
$database = $spanner
    ->instance($instanceId)
    ->database($databaseId, ['lock' => $lock]);
```

### Client-Side Metrics

[](#client-side-metrics)

The Cloud Spanner client library supports exporting built-in client-side metrics to Google Cloud Monitoring using OpenTelemetry. These metrics provide detailed observability into operations, RPC attempts, and Google Front End (GFE) or Spanner API Frontend (AFE) latencies.

To enable client-side metrics:

```
use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient([
    'enableBuiltInMetrics' => true,
    // optional: timeout in milliseconds for metric export calls
    'metricsTimeoutMillis' => 100
]);
```

All captured metrics are aggregated in-memory and exported synchronously during the PHP process shutdown phase.

Warning

**Performance Caveat**: Because PHP has a share-nothing architecture, exporting metrics synchronously at shutdown will add to the total request execution latency of the PHP process. For this reason, it is advised to enable built-in metrics primarily for debugging and active performance monitoring.

To minimize this performance overhead, installing the PECL [`ext-opentelemetry`](https://pecl.php.net/package/opentelemetry) extension is **highly recommended**.

#### Prerequisites

[](#prerequisites)

1. **IAM Permissions**: The credentials used by your application require `monitoring.timeSeries.create` permission to publish metrics. Predefined Spanner roles (such as `roles/spanner.databaseAdmin`, `roles/spanner.databaseUser`, and `roles/spanner.databaseReader`) already include this permission by default. If you are using a custom IAM role, ensure this permission is added.
2. **OpenTelemetry Extension**: Installing the [`ext-opentelemetry`](https://pecl.php.net/package/opentelemetry) PHP extension is highly advised to optimize metrics collection and export performance.

### Debugging

[](#debugging)

Please see our [Debugging guide](https://github.com/googleapis/google-cloud-php/blob/main/DEBUG.md)for more information about the debugging tools.

### Version

[](#version)

This component is considered GA (generally available). As such, it will not introduce backwards-incompatible changes in any minor or patch releases. We will address issues and requests with the highest priority.

### Next Steps

[](#next-steps)

1. Understand the [official documentation](https://cloud.google.com/spanner/docs/).
2. Take a look at [in-depth usage samples](https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/spanner/).

###  Health Score

72

—

ExcellentBetter than 100% of packages

Maintenance97

Actively maintained with recent releases

Popularity48

Moderate usage in the ecosystem

Community38

Small or concentrated contributor base

Maturity91

Battle-tested with a long release history

 Bus Factor4

4 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Total

200

Last Release

16d ago

Major Versions

v0.11.0 → v1.0.02017-12-22

v1.106.0 → v2.0.0-RC12025-10-20

PHP version history (3 changes)v1.58.3PHP &gt;=7.4

v1.74.0PHP ^8.0

v1.103.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/a8713415b20b4be4cec8f8b22741e3cd05f76eee9e38de1de5bf32727349b7c5?d=identicon)[bshaffer](/maintainers/bshaffer)

![](https://www.gravatar.com/avatar/3901206952845568d7557a60855b097f6d1bafaa7a24020cfcf5bb8de74f9d28?d=identicon)[google-cloud](/maintainers/google-cloud)

---

Top Contributors

[![release-please[bot]](https://avatars.githubusercontent.com/in/40688?v=4)](https://github.com/release-please[bot] "release-please[bot] (120 commits)")[![gcf-owl-bot[bot]](https://avatars.githubusercontent.com/in/99011?v=4)](https://github.com/gcf-owl-bot[bot] "gcf-owl-bot[bot] (83 commits)")[![yoshi-automation](https://avatars.githubusercontent.com/u/44816363?v=4)](https://github.com/yoshi-automation "yoshi-automation (70 commits)")[![jdpedrie](https://avatars.githubusercontent.com/u/89034?v=4)](https://github.com/jdpedrie "jdpedrie (69 commits)")[![bshaffer](https://avatars.githubusercontent.com/u/103941?v=4)](https://github.com/bshaffer "bshaffer (61 commits)")[![dwsupplee](https://avatars.githubusercontent.com/u/2079879?v=4)](https://github.com/dwsupplee "dwsupplee (32 commits)")[![larkee](https://avatars.githubusercontent.com/u/31196561?v=4)](https://github.com/larkee "larkee (16 commits)")[![vishwarajanand](https://avatars.githubusercontent.com/u/7369612?v=4)](https://github.com/vishwarajanand "vishwarajanand (16 commits)")[![michaelbausor](https://avatars.githubusercontent.com/u/14846209?v=4)](https://github.com/michaelbausor "michaelbausor (13 commits)")[![saranshdhingra](https://avatars.githubusercontent.com/u/1038319?v=4)](https://github.com/saranshdhingra "saranshdhingra (12 commits)")[![ajupazhamayil](https://avatars.githubusercontent.com/u/14087896?v=4)](https://github.com/ajupazhamayil "ajupazhamayil (10 commits)")[![Hectorhammett](https://avatars.githubusercontent.com/u/9062626?v=4)](https://github.com/Hectorhammett "Hectorhammett (9 commits)")[![ava12](https://avatars.githubusercontent.com/u/1997053?v=4)](https://github.com/ava12 "ava12 (7 commits)")[![AVaksman](https://avatars.githubusercontent.com/u/7764119?v=4)](https://github.com/AVaksman "AVaksman (6 commits)")[![danielgsims](https://avatars.githubusercontent.com/u/695933?v=4)](https://github.com/danielgsims "danielgsims (4 commits)")[![skuruppu](https://avatars.githubusercontent.com/u/951152?v=4)](https://github.com/skuruppu "skuruppu (3 commits)")[![chingor13](https://avatars.githubusercontent.com/u/32483?v=4)](https://github.com/chingor13 "chingor13 (2 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (2 commits)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (2 commits)")[![WeiranFang](https://avatars.githubusercontent.com/u/8175562?v=4)](https://github.com/WeiranFang "WeiranFang (2 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/google-cloud-spanner/health.svg)

```
[![Health](https://phpackages.com/badges/google-cloud-spanner/health.svg)](https://phpackages.com/packages/google-cloud-spanner)
```

###  Alternatives

[google/cloud-translate

Cloud Translation Client for PHP

20817.3M107](/packages/google-cloud-translate)[google/cloud-datastore

Cloud Datastore Client for PHP

241.2M23](/packages/google-cloud-datastore)[google/cloud-pubsub

Cloud PubSub Client for PHP

9118.9M79](/packages/google-cloud-pubsub)[google/cloud-firestore

Cloud Firestore Client for PHP

1834.5M32](/packages/google-cloud-firestore)[google/cloud-speech

Cloud Speech Client for PHP

591.9M3](/packages/google-cloud-speech)[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

346132.9M112](/packages/google-cloud-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
