LoginSignup
22
18

More than 5 years have passed since last update.

PHPでサービスアカウントを利用してCloud Firestoreにデータを追加してみる

Last updated at Posted at 2018-10-22

はじめに

Firebase とか Firestore とか単語だけは知ってるけど実際には使った事がない人がゼロからFirestoreにデータを突っ込むまでを記したものです
なにぶん右も左もわからぬ状態ですので、情報として正しくない可能性があるのでご注意下さい :angel_tone1:

慣れてしまえば簡単だがそうでない場合には長い長い前準備

大体は公式に書いてある通り

1. プロジェクト設定

  1. Firebaseコンソールで適当に新しいプロジェクトを作成
  2. Databaseセクションでデータベースの作成 ⇒ テストモードで開始 ⇒ 有効にする
  3. コレクションを追加 ⇒ コレクションIDに「users」 次へ ⇒ フィールドに「test」 保存

2. サービスアカウント設定

ここで作成されるJsonファイルはクレデンシャルな認証情報なので公開等は厳禁です

  1. サービスアカウント作成ページで適当に新しいサービスアカウントを作成
  2. APIとサービスセクションの認証情報で認証情報を作成 ⇒ サービス アカウント キー ⇒ 新しいサービスアカウント ⇒ サービス アカウント名に「test」、役割を「オーナー」、Jsonチェックボックス ⇒ 作成

3. 開発環境設定

  1. 開発環境で環境変数の設定
    export GOOGLE_APPLICATION_CREDENTIALS="さっきつくったJsonファイル"
  2. gRPCのインストール
  3. composer を利用して Cloud Firestore PHP のライブラリを追加
    composer require google/cloud-firestore

4. 適当にコーディング

なんとなく Lumen を利用しています
ControllerやDataSourcesは任意ですので、適宜読み替えて下さい

Controller.php
namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\DataSources\FireStore\FireStore;

class Controller extends BaseController
{
    private $fireStore;

    public function index()
    {
        $this->fireStore = app(FireStore::class);
        $this->fireStore->addData();
    }
}
Firestore.php
namespace App\DataSources\FireStore;

use App\DataSources\FireStore\FireStoreBase;

class FireStore extends FireStoreBase
{
    public function __construct()
    {
        parent::__construct("xxxxxxxxxxxx"); // Jsonに書いてあるproject_id
    }

    public function addData()
    {
        $docRef = $this->client->collection('users')->document('lovelace');
        $docRef->set([
            'first' => 'Ada',
            'last' => 'Lovelace',
            'born' => 1815
        ]);
        printf('Added data to the lovelace document in the users collection.' . PHP_EOL);   
    }
}
FireStoreBase.php
namespace App\DataSources\FireStore;

use Google\Cloud\Firestore\FirestoreClient;

abstract class FireStoreBase
{
    protected $client;

    public function __construct($projectId)
    {
        $this->client = new FirestoreClient([
            'projectId' => $projectId,
        ]);
    }
}

こんな感じで実行すると、FirebaseコンソールのDatabaseにデータが追加されます :tada:

最後に

右も左もわからない状態から初めて、ようやくテストデータが追加出来ました。
自分自身、かなり苦戦してしまったので、これが誰かの役に立てればと思います。
ありがとうございました :boy:

22
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
18