Installing Firebase in Codeigniter PHP
A while ago, I was struggling to write a query every time to fetch the data in MySQL since it is structured data and I wanted to install Firebase to shift my database into NoSQL structure.
Since there is no official documentation on Firebase for adding into Codeigniter or PHP. In this tutorial, I will let you know the simple steps to get started.
Pre-requisite
- You have your own CodeIgniter setup complete with basic views, models, and controllers.
- [Important] You are using Xampp version > 8.0 and PHP version > 8.0
Step 1: Go inside composer.json and add these lines inside “require”
"require": {
"php": ">=5.3.7",
"kreait/firebase-php": "^5.26",
"google/cloud-firestore": "^1.38"
}
Step 2: Open terminal/cmd into your project path and write
composer install
Note — Make sure it installs everything without any error.
Step 3: Go inside index.php and write the below line. It makes sure the libraries installed from the composer can be used in your project.
<?php
require_once __DIR__ . '/vendor/autoload.php';
Step 4: Open the Firebase console and go to Project Overview Settings -> Project Settings -> Service Accounts -> Generate new private key.
This will download a serviceKey.json file which we are going to use in the next step. Store this file inside the application -> config -> serviceKey.json
Step 5: Now create a file inside the application -> libraries -> Firebase.php and write this code in that file.
<?php
use Kreait\Firebase\Factory;
class Firebase {
protected $firestore;
public function __construct()
{
$serviceAccountPath = APPPATH . 'config/serviceKey.json';
// Initialize Firebase
$factory = (new Factory)
->withServiceAccount($serviceAccountPath);
$this->firestore = $factory->createFirestore();
}
public function getFirestore()
{
return $this->firestore;
}
}
Step 6: How to use this inside your controller method. So open your controller and write this inside your index() method
public function index()
{
$this->load->library('firebase');
$firestore = $this->firebase->getFirestore();
// Reference to a collection
$collection = $firestore->database()->collection('temp-collection');
$documents = $collection->documents();
foreach ($documents as $document) {
if ($document->exists()) {
echo 'Document data for document ' . $document->id() . ':' . PHP_EOL;
print_r($document->data());
echo PHP_EOL;
} else {
echo 'Document ' . $document->id() . ' does not exist!' . PHP_EOL;
}
}
$this->load->view('dashboard');
}
Open your browser and enter http://localhost/yourcodeignterfoldername/controller
This will give you the JSON result if there is a temp-collection inside your Firestore database.
That’s it. Happy Coding 😁
REFERENCE:
REACH OUT TO ME: