FireBase 是一個提供跨平台的雲端開發平台,可以讓開發者快速建立雲端的後端開發環境,包含本文將要介紹的即時資料庫(Realtime Database),是 FireBase 一個很熱門且核心的服務。
即時資料庫是一種 noSql 的結構,儲存結構類似於陣列或是 json 格式,如下圖
本次會介紹 kreait/firebase-php 這個套件,可以透過 composer 來安裝。本文的 Laravel 版本是 6.18 ,PHP 版本是 7.2。可以在專案底下用 php artisan --version 指令查看 Laravel 版本。
這邊很容易,依照步驟一步一步申請就好。
基本上做到這邊 FiraBase 專案就完成了!
再來要把網站加入到 FireBase
1. 先在首頁選擇新增網頁
2. 填入應用程式名稱,勾勾可以不打勾,看個人
3.完成之後會要求放一段 JavaScript 程式碼,這邊先跳過,回到主控台。
4.到左上角找到箭頭展開,選擇專案設定
5. 選擇服務帳戶
6. 選擇產生新的私密金鑰
這樣會下載到一個 json 檔案,大概長下面這樣,稍後會用到,注意檔案不要外洩。
{
"type": "service_account",
"project_id": "",
"private_key_id": "",
"private_key": ",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": ""
}
在左邊找到 Realtime Database,然後點選建立資料庫
然後這裡大概只能選美國
然後先暫時選擇測試模式,會允許所有的資料庫操作,日後再修改
按啟用之後就可以有資料庫了。
1.先到專案底下,執行指令安裝套件
composer require kreait/firebase-php
如果遇到記憶體不足的問題
Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52
Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.%
可以改用這個指令試試看
php -d memory_limit=-1 /usr/local/bin/composer require kreait/firebase-php
這樣會連同相依套件都安裝上了
2.建立 FirebaseController
php artisan make:controller FirebaseController
再來新增一些方法
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Database;
class FirebaseController extends Controller
{
public static function index()
{
$firebase = (new Factory)->withServiceAccount(__DIR__.'/Your.json')
->withDatabaseUri('YourURL')
->createDatabase();
$firebase -> getReference('posts') -> push([
'userID' => 'abc',
'content' => 'happy day'
]);
print_r($firebase -> getReference('posts') -> getvalue());
}
}
先把剛剛拿到的 json 檔案與 Controller 放在一起,再把檔名帶入到 Your.json 就好;而 YourURL 是在 Realtime Database 拿到的,如下圖:
3. 在 web.php 設定 route
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/firebaseTest','FirebaseController@index');
輸入指令執行專案
php artisan serve
然後瀏覽 http://127.0.0.1:8000/firebaseTest
成功的話就可以看到以下畫面
再去 Firebase 看資料庫已經有新增東西了
基本上這樣就已經完成了 Firebase 的設定了,一些關於 Realtime DataBase 的技巧就不在這邊介紹了。
如果有任何問題歡迎在底下留言告訴我。