ktamas77/firebase-php
PHP library for Firebase integration: access Realtime Database, Authentication and other Firebase services with a simple, lightweight API. Supports service account credentials, token handling, and common CRUD operations—useful for Laravel or any PHP app needing Firebase.
Installation
composer require ktamas77/firebase-php
Ensure your project has PHP 7.4+ and the ext-curl extension enabled.
First Use Case: Initialize Firebase
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/path/to/serviceAccountKey.json');
$firebase = (new Factory())
->withServiceAccount($serviceAccount)
->create();
Where to Look First
tests/ directory in the package for real-world usage patterns.Kreait\Firebase\Firebase and its sub-services (e.g., Database, Storage, Auth).$database = $firebase->database();
$ref = $database->getReference('users');
// Write data
$ref->set([
'user1' => ['name' => 'John', 'email' => 'john@example.com']
]);
// Read data
$snapshot = $ref->get();
$users = $snapshot->getValue();
// Listen for changes
$ref->on('value', function ($snapshot) {
$data = $snapshot->getValue();
// Handle update
});
$auth = $firebase->auth();
$user = $auth->createUser([
'email' => 'user@example.com',
'password' => 'securepassword123',
'emailVerified' => false,
]);
// Sign in
$customToken = $auth->createCustomToken('uid');
$storage = $firebase->storage();
$bucket = $storage->bucket('my-bucket');
// Upload file
$bucket->upload(
__DIR__.'/file.txt',
['name' => 'remote-file.txt']
);
// Download file
$file = $bucket->file('remote-file.txt');
$contents = $file->downloadToFile(__DIR__.'/downloaded.txt');
$firestore = $firebase->firestore();
$collection = $firestore->collection('posts');
// Add document
$collection->add(['title' => 'Hello World', 'content' => '...']);
// Query documents
$query = $collection->where('title', '==', 'Hello World');
$snapshot = $query->documents();
Dependency Injection: Register the Firebase client in Laravel's service container for easy access:
$app->singleton(Firebase::class, function ($app) {
return (new Factory())
->withServiceAccount(ServiceAccount::fromJsonFile(storage_path('app/firebase-key.json')))
->create();
});
Then inject Kreait\Firebase\Firebase into controllers/services.
Environment Configuration: Store the service account key path in .env:
FIREBASE_KEY_PATH=storage/app/firebase-key.json
Load it dynamically:
$serviceAccount = ServiceAccount::fromJsonFile(env('FIREBASE_KEY_PATH'));
Error Handling: Wrap Firebase operations in try-catch blocks to handle exceptions (e.g., Kreait\Firebase\Exception\FirebaseException):
try {
$snapshot = $ref->get();
} catch (\Kreait\Firebase\Exception\FirebaseException $e) {
Log::error('Firebase error: ' . $e->getMessage());
abort(500, 'Firebase operation failed');
}
Service Account Key Permissions
database.readWrite, storage.objectAdmin).Rate Limiting and Throttling
use Kreait\Firebase\Exception\FirebaseException;
use Kreait\Firebase\Exception\RateLimitExceeded;
try {
$snapshot = $ref->get();
} catch (RateLimitExceeded $e) {
sleep(2); // Wait before retrying
retry();
}
Offline Persistence
$database = $firebase->database();
$database->getReference()->setPersistenceEnabled(false);
Timeouts
$database->getReference()->setTimeout(30); // 30 seconds
CORS Issues
firebase emulators:start
Enable Debug Logging Configure Monolog to log Firebase events:
$factory = (new Factory())
->withLogger(new \Monolog\Logger('firebase', [
new \Monolog\Handler\StreamHandler(storage_path('logs/firebase.log')),
]));
Check HTTP Requests Use tools like Postman or Charles Proxy to inspect raw HTTP requests/responses between your app and Firebase.
Validate JSON Keys Ensure the service account JSON key is valid and not corrupted. Test it with:
firebase deploy --only functions --json-key path/to/serviceAccountKey.json
Custom Middleware Add middleware to Firebase operations (e.g., logging, auth checks):
$database->getReference()->addMiddleware(function ($request) {
Log::info('Firebase DB request:', $request->getData());
return $request;
});
Event Listeners Extend the package by listening to Firebase events (e.g., Realtime Database value changes):
$ref->on('value', function ($snapshot) {
event(new FirebaseDataUpdated($snapshot->getName(), $snapshot->getValue()));
});
Testing
Use the Kreait\Firebase\Test\TestDouble trait to mock Firebase services in PHPUnit:
use Kreait\Firebase\Test\TestDouble;
class MyTest extends TestCase
{
use TestDouble;
public function testFirebaseOperation()
{
$this->mockFirebaseDatabase();
// Test logic here
}
}
Async Operations For long-running tasks, use Laravel Queues to offload Firebase operations:
dispatch(new UploadToFirebase($filePath, $bucketName));
Then implement the job:
public function handle()
{
$storage = app(Firebase::class)->storage();
$bucket = $storage->bucket($this->bucketName);
$bucket->upload($this->filePath, ['name' => 'uploaded-' . time() . '.txt']);
}
How can I help you explore Laravel packages today?