LoginSignup
19
20

More than 5 years have passed since last update.

PHPでFirebase Realtime Databaseを使ってみよう!

Last updated at Posted at 2018-01-04

はじめに

「php firebase」とGoogle検索すると2018/01/04現在で下記の記事がトップに表示されますが、
認証などが変わっているため新しくメモとして残しておきたいと思います。

FirebaseにはRealtime Database以外の機能も豊富にありますが、realtime databaseのみをターゲットとします。

プロジェクトの作成

コンソール(https://console.firebase.google.com/ )へ行き新規プロジェクトを作成します。

firebase_credentials.jsonの取得

今回は、Googleサービスアカウントを使ってリクエストの認証を行います。
下記に手順が記載されています。

  1. プロジェクトの設定ページの [サービス アカウント] タブに移動します。
  2. Firebase プロジェクトを選択します。まだプロジェクトがない場合は、[新規プロジェクトを作成] をクリックします。アプリに関連付けられた既存の Google プロジェクトがある場合は、[Google プロジェクトをインポート] をクリックします。
  3. [サービス アカウント] タブの [Firebase Admin SDK] セクション下部にある [新しい秘密鍵を生成] ボタンをクリックします。

利用するライブラリ

Firebase Admin SDK for PHP
https://github.com/kreait/firebase-php/
http://firebase-php.readthedocs.io/en/stable/index.html

インストール方法

composerを利用してインストール

php composer.phar require kreait/firebase-php ^3.0

すでにcomposer.jsonがある場合は、下記を追加


 {
   "require": {
      "kreait/firebase-php": "^3.0"
   }
 }

Googleサービスアカウントでの認証

今回は、Googleサービスアカウントを使ってリクエストの認証を行います。
事前に取得したjsonファイルをfromJsonfileメソッドの引数として指定します。

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/firebase_credentials.json');
$firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    ->create();

データベースインスタンスの生成

use Kreait\Firebase;

$firebase = (new Firebase\Factory())->create();
$database = $firebase->getDatabase();

データの取得

$reference = $database->getReference('path/to/child/location');

$snapshot = $reference->getSnapshot();

$value = $snapshot->getValue();
// or
$value = $reference->getValue();

データの保存

$db->getReference('config/website')
   ->set([
       'name' => 'My Application',
       'emails' => [
           'support' => 'support@domain.tld',
           'sales' => 'sales@domain.tld',
       ],
       'website' => 'https://app.domain.tld',
      ]);

$db->getReference('config/website/name')->set('New name');
19
20
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
19
20