Reference documentation and code samples for the Cloud Firestore Client class FirestoreClient.
Cloud Firestore is a flexible, scalable, realtime database for mobile, web, and server development.
In production environments, it is highly recommended that you make use of the Protobuf PHP extension for improved performance. Protobuf can be installed via PECL.
$ pecl install protobuf
To enable the
Google Cloud Firestore Emulator,
set the FIRESTORE_EMULATOR_HOST
to the value provided by the gcloud command.
Please note that Google Cloud PHP currently does not support IPv6 hostnames.
If the Firestore emulator provides a IPv6 hostname, or a comma-separated list
of both IPv6 and IPv4 names, be sure to set the environment variable to only
an IPv4 address. The equivalent of [::1]:8080
, for instance, would be
127.0.0.1:8080
.
Example:
use Google\Cloud\Firestore\FirestoreClient;
$firestore = new FirestoreClient();
// Using the Firestore Emulator
use Google\Cloud\Firestore\FirestoreClient;
// Be sure to use the port specified when starting the emulator.
// `8900` is used as an example only.
putenv('FIRESTORE_EMULATOR_HOST=localhost:8900');
$firestore = new FirestoreClient();
Methods
__construct
Create a Firestore client. Please note that this client requires the gRPC extension.
Parameters | |
---|---|
Name | Description |
config |
array
Configuration Options. |
↳ apiEndpoint |
string
A hostname with optional port to use in place of the service's default endpoint. |
↳ projectId |
string
The project ID from the Google Developer's Console. |
↳ authCache |
CacheItemPoolInterface
A cache for storing access tokens. Defaults to a simple in memory implementation. |
↳ authCacheOptions |
array
Cache configuration options. |
↳ authHttpHandler |
callable
A handler used to deliver Psr7 requests specifically for authentication. |
↳ httpHandler |
callable
A handler used to deliver Psr7 requests. Only valid for requests sent over REST. |
↳ keyFile |
array
The contents of the service account credentials .json file retrieved from the Google Developer's Console. Ex: |
↳ keyFilePath |
string
The full path to your service account credentials .json file retrieved from the Google Developers Console. |
↳ retries |
int
Number of retries for a failed request. Defaults to |
↳ scopes |
array
Scopes to be used for the request. |
↳ quotaProject |
string
Specifies a user project to bill for access charges associated with the request. |
↳ returnInt64AsObject |
bool
If true, 64 bit integers will be returned as a Google\Cloud\Firestore\Google\Cloud\Core\Int64 object for 32 bit platform compatibility. Defaults to false. |
batch
Get a Batch Writer
The Google\Cloud\Firestore\Google\Cloud\Firestore\WriteBatch allows more performant multi-document, atomic updates.
Example:
$batch = $firestore->batch();
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\WriteBatch |
bulkWriter
Get a Bulk Writer
Google\Cloud\Firestore\Google\Cloud\Firestore\BulkWriter allows scheduling multiple writes with auto-retries in batches. Please note:
- This method is blocking and may execute many sequential batch write requests.
- Gradually ramps up writes as specified by the 500/50/5 rule.
- Does not guarantee the order of writes.
- Accepts unique document references only. Read more: Ramping up traffic
Example:
$batch = $firestore->bulkWriter();
Parameters | |
---|---|
Name | Description |
options |
array
Configuration options.
|
↳ maxBatchSize |
int
Maximum number of requests per batch. Defaults to |
↳ greedilySend |
bool
Flag to indicate whether BulkWriter greedily sends batches. Defaults to |
↳ isThrottlingEnabled |
bool
Flag to indicate whether rate of sending writes can be throttled. Defaults to |
↳ initialOpsPerSecond |
int
Initial number of operations per second. Defaults to |
↳ maxOpsPerSecond |
int
Maximum number of operations per second. Defaults to |
↳ isRetryable |
callable
Default retry handler for individial writes status code to be retried. Should accept error code and return true if retryable. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\BulkWriter |
collection
Lazily instantiate a Collection reference.
Collections hold Firestore documents. Collections cannot be created or deleted directly - they exist only as implicit namespaces. Once no child documents remain in a collection, it ceases to exist.
Example:
$collection = $firestore->collection('users');
Parameter | |
---|---|
Name | Description |
name |
string
The name of the collection. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\CollectionReference |
collections
List root-level collections in the database.
Example:
$collections = $firestore->collections();
Parameters | |
---|---|
Name | Description |
options |
array
Configuration options |
↳ pageSize |
int
Maximum number of results to return per request. |
↳ resultLimit |
int
Limit the number of results returned in total. Defaults to |
↳ pageToken |
string
A previously-returned page token used to resume the loading of results from a specific point. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\firestore\collectionreference> |
document
Get a reference to a Firestore document.
Example:
$document = $firestore->document('users/john');
Parameter | |
---|---|
Name | Description |
name |
string
The document name or a path, relative to the database. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\DocumentReference |
documents
Get a list of documents by their path.
The number of results generated will be equal to the number of documents requested, except in case of error.
Note that this method will always return instances of Google\Cloud\Firestore\Google\Cloud\Firestore\DocumentSnapshot, even if the documents requested do not exist. It is highly recommended that you check for existence before accessing document data.
Example:
$documents = $firestore->documents([
'users/john',
'users/dave'
]);
// To check whether a given document exists, use `DocumentSnapshot::exists()`.
$documents = $firestore->documents([
'users/deleted-user'
]);
foreach ($documents as $document) {
if (!$document->exists()) {
echo $document->id() . ' Does Not Exist';
}
}
Parameters | |
---|---|
Name | Description |
paths |
string[]|array<Google\Cloud\Firestore\DocumentReference>
Any combination of string paths or DocumentReference instances. |
options |
array
Configuration options. |
Returns | |
---|---|
Type | Description |
array<Google\Cloud\Firestore\DocumentSnapshot> |
collectionGroup
Creates a new Query which includes all documents that are contained in a collection or subcollection with the given collection ID.
A collection group query with a collection ID of foo
will return
documents from /foo
and /abc/dce/foo
, but not /foo/abc/dce
.
Example:
$query = $firestore->collectionGroup('users');
$querySnapshot = $query->documents();
echo sprintf('Found %d documents!', $querySnapshot->size());
Parameter | |
---|---|
Name | Description |
id |
string
Identifies the collection to query over. Every collection or subcollection with this ID as the last segment of its path will be included. May not contain a slash. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\Query |
runTransaction
Executes a function in a Firestore transaction.
Transactions offer atomic operations, guaranteeing that either all writes will be applied, or none will be applied. The Google Cloud PHP Firestore client also handles automatic retry in cases where transactions fail due to a retryable error.
Transactions will be committed once the provided callable has finished execution. Thrown exceptions will prevent commit and trigger a rollback, and will bubble up to your level to be handled in whatever fashion is appropriate.
This method returns the return value of the given transaction callable.
Example:
use Google\Cloud\Firestore\Transaction;
$transferAmount = 500.00;
$from = $firestore->document('users/john');
$to = $firestore->document('users/dave');
$toNewBalance = $firestore->runTransaction(function (Transaction $t) use ($from, $to, $transferAmount) {
$fromSnapshot = $t->snapshot($from);
$toSnapshot = $t->snapshot($to);
$fromNewBalance = $fromSnapshot['balance'] - $transferAmount;
$toNewBalance = $toSnapshot['balance'] + $transferAmount;
// If the transaction cannot be completed, throwing any exception
// will trigger a rollback operation.
if ($fromNewBalance < 0) {
throw new \Exception('User 1 has insufficient funds!');
}
$t->update($from, [
['path' => 'balance', 'value' => $fromNewBalance]
])->update($to, [
['path' => 'balance', 'value' => $toNewBalance]
]);
return $toNewBalance;
});
Parameters | |
---|---|
Name | Description |
callable |
callable
A callable function, allowing atomic operations
against the Firestore API. Function signature should be of form:
|
options |
array
Configuration Options. |
↳ begin |
array
Configuration options for BeginTransaction. |
↳ commit |
array
Configuration options for Commit. |
↳ rollback |
array
Configuration options for rollback. |
↳ maxRetries |
int
The maximum number of times to retry failures. Defaults to |
Returns | |
---|---|
Type | Description |
mixed |
geoPoint
Create a new GeoPoint
Example:
$geoPoint = $firestore->geoPoint(37.4220, -122.0841);
Parameters | |
---|---|
Name | Description |
latitude |
float
The latitude |
longitude |
float
The longitude |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\GeoPoint |
blob
Create a new Blob
Example:
$blob = $firestore->blob('hello world');
// Blobs can be used to store binary data
$blob = $firestore->blob(file_get_contents(__DIR__ .'/family-photo.jpg'));
Parameter | |
---|---|
Name | Description |
value |
string|resource|Psr\Http\Message\StreamInterface
The value to store in a blob. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Blob |
fieldPath
Returns a FieldPath class, referring to a field in a document.
The path may consist of a single field name (referring to a top-level field in the document), or a list of field names (referring to a nested field in the document).
Example:
$path = $firestore->fieldPath(['accounts', 'usd']);
Parameter | |
---|---|
Name | Description |
fieldNames |
array
A list of field names. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\FieldPath |
sessionHandler
Returns a FirestoreSessionHandler.
Example:
$handler = $firestore->sessionHandler();
// Configure PHP to use the Firestore session handler.
session_set_save_handler($handler, true);
session_save_path('sessions');
session_start();
// Then write and read the $_SESSION array.
$_SESSION['name'] = 'Bob';
echo $_SESSION['name'];
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options. |
↳ gcLimit |
int
The number of entities to delete in the garbage collection. Values larger than 500 will be limited to 500. Defaults to |
↳ collectionNameTemplate |
string
A sprintf compatible template for formatting the collection name where sessions will be stored. The template receives two values, the first being the save path and the latter being the session name. |
↳ begin |
array
Configuration options for beginTransaction. |
↳ commit |
array
Configuration options for commit. |
↳ rollback |
array
Configuration options for rollback. |
↳ read |
array
Configuration options for read. |
↳ query |
array
Configuration options for runQuery. |
Returns | |
---|---|
Type | Description |
Google\Cloud\Firestore\FirestoreSessionHandler |
Constants
VERSION
Value: '1.27.3'
DEFAULT_DATABASE
Value: '(default)'
FULL_CONTROL_SCOPE
Value: 'https://www.googleapis.com/auth/cloud-platform'
MAX_RETRIES
Value: 5