Yii2 with Google Firestore

So I have a Yii2 advanced template set up, and I need Firestore as my database. I’ve looked up the docs at https://github.com/googleapis/google-cloud-php-firestore#sample and https://github.com/googleapis/google-cloud-php/blob/master/AUTHENTICATION.md#client-authentication, but I cannot figure out how to put it into Yii2; does anyone have any suggestions? I have all the necessary composer libraries installed. The Yii extension for Firestore seems a little outdated…


Have you tried the sample code provided in googe-cloud-php-firestore README ? What did not work ?

What Yii extension are you referring to? There is no official one.

I don’t know where to put the code, mainly. (I’m still trying to figure out where everything goes in Yii.) Meaning, what file should I put it in? I tried sticking two files authenticateCloud.php and initializeFirestore.php in a random folder called files under common, but it doesn’t sem to work…

No, it is not an official extension (https://github.com/gsposato/yii2-firestore). Sorry I forgot to mention that.

Ok, so first thing first, let’s start with a simple test to check if everything works. We’ll worry about where to put what and when later :slight_smile:

Create a new actionTest in your SiteController for example, and put the code inside it.

It could go like the following if you use the projectId property to authenticate

class SiteController extends \yii\web\Controller {
    // .. existing code

    public function actionTest($projectId)
        $firestore = new FirestoreClient(['projectId' => $projectId]);

        $collectionReference = $firestore->collection('YourCollection');
        $documentReference = $collectionReference->documents();
        $snapshot = $documentReference->snapshot();

        echo "Got " . count($snapshot) . " snapshots";


and call /site/test?projectId=your-firestore-project-id

I’ve tested it, and it works fine :smiley:

1 Like

Should I disable components/db in main-local.php or work around it or something?

Great news! Always use this approach when discovering something new: make it work, try it out, then ask yourself architectural questions :slight_smile:

Now about where to place your code, you should study your use cases with firestore. Where are you going to use it? How? I’d probably start by a \app\helpers\Firestore helper.

I would also study the few yii2 extensions dealing with firestore. What do they bring to the table? How are they structured. (Disclaimer: they can be utterly sophisticated and complicated where you don’t need that at all, again, your use case should tell you that)

About the DB component, I’d simply leave it unconfigured as you may need it later in your project.

1 Like