PHP code example of ldkafka / yii3-google-firestore

1. Go to this page and download the library: Download ldkafka/yii3-google-firestore library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ldkafka / yii3-google-firestore example snippets


use HttpSoft\Message\RequestFactory;
use HttpSoft\Message\ResponseFactory;
use HttpSoft\Message\StreamFactory;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\Psr18Client;

$http = new Psr18Client(HttpClient::create(['timeout' => 10, 'max_duration' => 30]), new ResponseFactory(), new StreamFactory());
$requests = new RequestFactory();
$streams = new StreamFactory();

$http = new GuzzleHttp\Client(['connect_timeout' => 10, 'timeout' => 30]);
$requests = $streams = new GuzzleHttp\Psr7\HttpFactory();

use Ldkafka\GoogleFirestore\Auth\ServiceAccountCredentials;
use Ldkafka\GoogleFirestore\FirestoreClient;

$credentials = new ServiceAccountCredentials('/run/secrets/firestore.json', $http, $requests, $streams);
$fs = new FirestoreClient($http, $requests, $streams, $credentials);   // project from the key, database (default)

$result = $fs->create('messages', ['to' => 'infra', 'subject' => 'Feed 13752', 'status' => 'new']);
$message = $fs->get($result->path);
echo $message?->get('subject');

use Ldkafka\GoogleFirestore\Precondition;

$doc = $fs->get('messages/abc');                       // Document or null
$docs = $fs->getAll(['messages/a', 'messages/b']);    // ['messages/a' => Document|null, ...] in the order asked

$fs->create('messages', $data);                        // random 20-character id, made on the client
$fs->create('messages', $data, 'abc');                 // AlreadyExistsException if 'messages/abc' exists

$fs->set('messages/abc', $data);                       // replace (creates it if missing)
$fs->set('messages/abc', ['meta' => ['seen' => true]], merge: true);   // only meta.seen changes

$fs->update('messages/abc', ['status' => 'seen', 'meta.by' => 'steward']);  // NotFoundException if missing
$fs->update('messages/abc', ['status' => 'done'], Precondition::updateTime($doc->updateTime));

$fs->delete('messages/abc');
$fs->delete('messages/abc', Precondition::exists());   // NotFoundException if missing

$inbox = $fs->query('messages')
    ->where('to', '==', 'infra')
    ->where('status', 'in', ['new', 'seen'])
    ->orderBy('createdAt', 'DESC');

$page1 = $inbox->limit(20)->get();                                       // list<Document>
$page2 = $inbox->limit(20)->startAfter($page1[count($page1) - 1])->get(); // cursor from the last document
foreach ($inbox->stream(pageSize: 200) as $doc) { /* every match, page by page */ }
$open = $inbox->count();

$fs->query('threads/t1/replies')->get();                                 // a subcollection
$fs->collectionGroup('replies')->where('author', '==', 'infra')->get();  // every 'replies' collection
$fs->listCollections();                                                  // ['messages', 'threads']
$fs->listCollections('threads/t1');                                      // a document's subcollections

use Ldkafka\GoogleFirestore\FieldValue;
use Ldkafka\GoogleFirestore\Transaction;
use Ldkafka\GoogleFirestore\Value\Reference;

$batch = $fs->batch();
$path = $batch->create('messages', ['to' => 'steward', 'createdAt' => FieldValue::serverTimestamp()]);
$batch->update('threads/t1', ['last' => new Reference($path)]);
$batch->delete('messages/old-1');
$results = $batch->commit();             // list<WriteResult>, one per write, in order; all or nothing

$n = $fs->runTransaction(function (Transaction $tx): int {
    $counter = $tx->get('counters/messages');
    $n = (int) ($counter?->get('n') ?? 0) + 1;
    $tx->set('counters/messages', ['n' => $n]);
    return $n;
});

$fs->update('messages/' . $id, [
    'status'    => 'done',
    'doneAt'    => FieldValue::serverTimestamp(),
    'attempts'  => FieldValue::increment(1),
    'labels'    => FieldValue::arrayUnion('infra', 'urgent'),
    'watchers'  => FieldValue::arrayRemove('steward'),
    'meta'      => ['at' => FieldValue::serverTimestamp()],
]);

use Ldkafka\GoogleFirestore\Exception\FailedPreconditionException;
use Ldkafka\GoogleFirestore\Exception\NotFoundException;

$candidates = $fs->query('messages')
    ->where('to', '==', 'infra')->where('status', '==', 'new')
    ->orderBy('createdAt')->limit(5)->get();

foreach ($candidates as $msg) {
    try {
        $fs->update($msg->path, [
            'status'    => 'claimed',
            'claimant'  => 'infra',
            'claimedAt' => FieldValue::serverTimestamp(),
        ], Precondition::updateTime($msg->updateTime));
        handle($msg);                     // only one agent gets here for this message
        break;
    } catch (FailedPreconditionException | NotFoundException) {
        continue;                         // another agent changed or removed it first
    }
}

$fs = new FirestoreClient($http, $requests, $streams, null, 'demo-project', emulatorHost: '127.0.0.1:8080');

// config/params.php of your application
'ldkafka/yii3-google-firestore' => [
    'keyFile' => '/run/secrets/firestore.json',   // empty = GOOGLE_APPLICATION_CREDENTIALS
    'projectId' => '',                            // empty = the key's project_id
    'databaseId' => '(default)',
    'emulatorHost' => '',                         // empty = FIRESTORE_EMULATOR_HOST; set = no login
    'useCache' => true,                           // the app's PSR-16 cache for the token
    'retry' => ['maxRetries' => 3, 'baseDelayMs' => 200, 'maxDelayMs' => 5000, 'transactionAttempts' => 5],
],