Idiomatic PHP client for Cloud Spanner.
NOTE: This repository is part of 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.
To begin, install the preferred dependency manager for PHP, Composer.
Now install this component:
$ composer require google/cloud-spannerThis component requires the gRPC extension. Please see our gRPC installation guide for more information on how to configure the extension.
Please see our Authentication guide for more information on authenticating your client. Once authenticated, you'll be ready to start making requests.
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'];The V2 version of the Spanner Client Library for PHP uses 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.
The session cache is configured with a default cache which uses the PSR-6 compatible SysvCacheItemPool
when the sysvshm extension is enabled, and FileSystemCacheItemPool 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]);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();Locking occurs when a new session is created, and ensures no race conditions occur when a session expires.
Locking uses a Semaphore lock when sysvmsg, sysvsem, and sysvshm extensions are enabled, and a
Flock lock otherwise. To configure a custom lock, supply a class implementing
LockInterface when calling Instance::database. Here's an example which encorporates the
Symfony Lock component:
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]);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 extension is highly recommended.
- IAM Permissions & OAuth Scopes: The credentials used by your application require the
monitoring.timeSeries.createpermission (provided by the Metric Writer roleroles/monitoring.metricWriter). Standard Spanner roles (roles/spanner.databaseAdmin,roles/spanner.databaseUser, androles/spanner.databaseReader) already include this permission.- When using Application Default Credentials (ADC) or keyfiles, the required
https://www.googleapis.com/auth/monitoring.writeOAuth scope is automatically configured. - If you supply a pre-instantiated credentials object (implementing
FetchAuthTokenInterfaceorCredentialsWrapper), ensure thathttps://www.googleapis.com/auth/monitoring.write(orhttps://www.googleapis.com/auth/cloud-platform) scope is included when creating your credentials object.
- When using Application Default Credentials (ADC) or keyfiles, the required
- OpenTelemetry Extension: Installing the
ext-opentelemetryPHP extension is highly advised to optimize metrics collection and export performance.
Individual calls accept a timeoutMillis option. To change the default deadline for every call a
client makes, pass a clientConfig array. SpannerClient builds three generated clients from the
same options, so the config has to cover all three interfaces:
use Google\Cloud\Spanner\SpannerClient;
$timeoutMillis = 5000;
$configFiles = [
'src/V1/resources/spanner_client_config.json',
'src/Admin/Instance/V1/resources/instance_admin_client_config.json',
'src/Admin/Database/V1/resources/database_admin_client_config.json',
];
$clientConfig = ['interfaces' => []];
foreach ($configFiles as $configFile) {
$path = $vendorDir . '/google/cloud-spanner/' . $configFile;
$decoded = json_decode(file_get_contents($path), true);
foreach ($decoded['interfaces'] as $interface => $settings) {
foreach (array_keys($settings['methods']) as $method) {
$settings['methods'][$method]['timeout_millis'] = $timeoutMillis;
}
foreach (array_keys($settings['retry_params']) as $name) {
$settings['retry_params'][$name]['initial_rpc_timeout_millis'] = $timeoutMillis;
$settings['retry_params'][$name]['max_rpc_timeout_millis'] = $timeoutMillis;
$settings['retry_params'][$name]['total_timeout_millis'] = $timeoutMillis;
}
$clientConfig['interfaces'][$interface] = $settings;
}
}
$spanner = new SpannerClient(['clientConfig' => $clientConfig]);Warning
Setting timeout_millis on its own has no effect on retryable methods — it only supplies
noRetriesRpcTimeoutMillis. The retry_params values are what determine the deadline, which is
why they are overridden above. Likewise, a config containing only google.spanner.v1.Spanner
leaves the admin clients without retry settings and calls to them fail with a TypeError. Read
the shipped JSON files at runtime rather than copying them into your project, so that methods
added in later releases are picked up.
See the Client Configuration guide for the full set of retry and timeout options.
Please see our Debugging guide for more information about the debugging tools.
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.
- Understand the official documentation.
- Take a look at in-depth usage samples.