Adding Firebase PHP to your project using Composer

Overview

Firebase PHP Client

Current version Supported PHP version Total Downloads

Build Status Build Status Scrutinizer Quality Score

Visual Source

❤️ Sponsor

Based on the Firebase REST API.

Available on Packagist.

Adding Firebase PHP to your project using Composer

For PHP 7 or later

composer require ktamas77/firebase-php

For PHP 5 use v2.2.4

composer require ktamas77/firebase-php:2.2.4

More info about Composer at getcomposer.org.

Example

// Firebase Token can be found in the Firebase Console:
// Settings -> Project Settings -> Service accounts -> Database secrets

const URL = 'https://kidsplace.firebaseio.com/';
const TOKEN = 'MqL0c8tKCtheLSYcygYNtGhU8Z2hULOFs9OKPdEp';
const PATH = '/firebase/example';

use Firebase\FirebaseLib;

$firebase = new FirebaseLib(URL, TOKEN);

// Storing an array
$test = [
    'foo' => 'bar',
    'i_love' => 'lamp',
    'id' => 42
];
$dateTime = new DateTime();
$firebase->set(PATH . '/' . $dateTime->format('c'), $test);

// Storing a string
$firebase->set(PATH . '/name/contact001', 'John Doe');

// Reading the stored string
$name = $firebase->get(PATH . '/name/contact001');

Supported Commands

setToken($token); // set up Firebase token $firebase->setBaseURI($uri); // set up Firebase base URI (root node) $firebase->setTimeOut($seconds); // set up maximum timeout / request">
// Firebase API commands

$firebase->set($path, $value);   // stores data in Firebase
$value = $firebase->get($path);  // reads a value from Firebase
$firebase->delete($path);        // deletes value from Firebase
$firebase->update($path, $data); // updates data in Firebase
$firebase->push($path, $data);   // push data to Firebase

// Query Parameters can be optionally used on all operations, example:

$value = $firebase->get($path, ['shallow' => 'true']);

// Query Parameter values with quotes example
// Documentation: https://firebase.google.com/docs/database/rest/retrieve-data#filtering-by-a-specified-child-key

$value = $firebase->get($path, ['orderBy' => '"height"']);

// Firebase PHP Library commands

$firebase->setToken($token);     // set up Firebase token
$firebase->setBaseURI($uri);     // set up Firebase base URI (root node)
$firebase->setTimeOut($seconds); // set up maximum timeout / request

Please refer to the Firebase REST API documentation for further details.

Composer upgrade

Coding standards check / fixing & tests are integrated with composer. To start, upgrade the required packages:

$ composer update

Unit Tests

All the unit tests are found in the "/tests" directory. Due to the usage of an interface, the tests must run in isolation.

The firebaseLib tests have inherent latency due to actual cURL calls to a live firebaseIO account. The firebaseLib tests can be executed by running the following command:

$ composer test

Coding Standards Validation

The codebase is in compliance with PSR-2.

To test coding standards:

$ composer style

To automatically fix standards (whenever it's possible):

$ composer style-fix

The MIT License (MIT)

Copyright (c) 2012-2021 Tamas Kalman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Comments
  • Why not take advantage of Keep-Alive?

    Why not take advantage of Keep-Alive?

    firebase-php promptly closes the curl handle after each request, making it impossible to take advantage of the underlying protocol's Keep-Alive capability. Since all Firebase API requests use SSL, using Keep-Alive would save a massive amount of time and resources (SSL handshake in addition to TCP handshake) when multiple requests are made in quick succession.

    Enabling Keep-Alive with PHP curl is as simple as reusing the same curl handle without closing it.

    opened by kijin 10
  • New firebase authentication

    New firebase authentication

    Firebase created a new authentication putting only the secret key returns "Cannot parse token". Now this module only works in public firebase database. Kindly help to resolve this issue.

    opened by kevin1193 9
  • _getJsonPath function doesn't allow query strings

    _getJsonPath function doesn't allow query strings

    The Firebase API offers orderBy and advanced query options. The _getJsonPath function currently appends ".json" to the end of the path without regard to the $path. This should be corrected so that query strings can be passed in the $path.

    I may fork and solve, but at least wanted the issue reported in case I don't get back here.

    enhancement 
    opened by solyoung 6
  • Adding extra query support

    Adding extra query support

    idea:

    $usersData = $firebase->get('/users', [
    'orderBy'      => 'id',
    'startAt'      => '1',
    'limitToFirst' => '80',
    ]);
    

    this is good for pagination and other things.

    opened by patrioticcow 5
  • Reuse curl handle to improve performance; fixes #14

    Reuse curl handle to improve performance; fixes #14

    I removed all instances of curl_close() and turned $ch into a property so that the HTTP connection will stay open (using KeepAlive) throughout the lifetime of the object.

    All unit tests seem to be passing, but there may be special cases not covered by the tests (e.g. what if the server drops the connection in between two requests?) so very thorough testing is recommended.

    opened by kijin 5
  • Can't use Query string with get method

    Can't use Query string with get method

    Hi, I've used the "get" method to retrieve query data, but it seem didn't work, the error is: { "error" : "Constraint index field must be a JSON primitive" } Pls note that if I put the URL on address bar, I still can get the matched data https://goldenmuse.firebaseio.com/user.json?orderBy="email"&startAt="[email protected]"&endAt="[email protected]" Could anyone help me resolve this? Thanks.

    Related issue: https://github.com/ktamas77/firebase-php/issues/19 Related PR: https://github.com/ktamas77/firebase-php/pull/25/files

    opened by bangank36 4
  • The actual Firebase class seems to be missing?

    The actual Firebase class seems to be missing?

    I'm probably an idiot for asking this, but when running the example I get this:

    Fatal error: Class 'Firebase' not found in (.....)/firebase-php/index.php on line 8

    The code I'm using is this:

    <?php
    require 'autoload.php';
    
    const DEFAULT_URL = 'https://xxxx.firebaseio.com';
    const DEFAULT_TOKEN = 'yyyy';
    const DEFAULT_PATH = '';
    
    $firebase = new Firebase(DEFAULT_URL, DEFAULT_TOKEN);
    
    $test = array(
        "foo" => "bar",
        "i_love" => "lamp",
        "id" => 42
    );
    
    $dateTime = new DateTime();
    
    $firebase->set(DEFAULT_PATH . '/' . $dateTime->format('c'), $test);
    
    ?>
    
    opened by koppelaar 4
  • New interface for advanced phpunit testing and phpunit testing on the firebaseLib

    New interface for advanced phpunit testing and phpunit testing on the firebaseLib

    Tamas,

    Thanks for your work on the firebase-php library. You really saved me on a project I am working on.

    In my project, I wanted to use phpunit to test without any latency. As such, I wrote an interface to be consumed by both the firebaseLib and a new firebaseStub that I created for phpunit testing.

    In the course, of adding the firebaseStub, I noticed that your unit tests did not actually verify the results from firebase. So, I converted your tests into phpunit tests. To make all of this happen, I need to add a few directories: lib and tests.

    I also added an additional validation for the baseURI during the class initialization.

    In addition, I updated the README file to include all of the changes with explanations of how to use the Stub for testing.

    Let me know, how I can help merge this code.

    opened by brianpilati 4
  • Running too slow

    Running too slow

    Hello, the script works very slow to 7 seconds to perform each operation, I know that the response of the firebase is fast so I wonder how it does to improve the response speed performance of the script.

    opened by ivent 3
  • Too Sloooooow

    Too Sloooooow

    Hi guys. I tried really everything, but it still slow. I even implemented "use one curl for all quests" but it still slow. I have ten quests and I wait for page 7sec. which is too much. Please help, I need to finish project.

    opened by zivoradmilekic 3
  • Refactor of the Firebase library

    Refactor of the Firebase library

    Hey Tamas - Decided to work on your firebase library today. Here is a summary of the changes.

    • Moved files around to follow the common conventions
    • Added a Namespace
    • Added Docblocks
    • Updated gitignore a bit to ignore composer stuff and composer.json so the FirebaseLib will be autoloaded
    • Added an Autoloader and phpunit xml files
    • Renamed main class name to look/work better with the namespace
    • Added an example to the readme
    opened by llbbl 3
  • Requirements?

    Requirements?

    Are requirements available anywhere? By requirements, I mean:

    • minimal PHP version
    • can it work without Composer
    • can it work on a shared hosting
    • is HTTPS mandatory
    opened by SmileSoftSr 0
  • Composer with php7.3 first time install issue:

    Composer with php7.3 first time install issue:

    Just downloaded composer for the first time, and trying to install the php-firebase admin panel using:

    composer require kreait/firebase-php ^4.35

    Resulting output: `Using version ^4.35 for kreait/firebase-php ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev)

    Installation failed, deleting ./composer.json.

    [ErrorException] "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

    require [--dev] [--prefer-source] [--prefer-dist] [--no-plugins] [--no-progress] [--no-update] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] []...`

    opened by Fever905 1
  • Getting unexpected error code 0/null/100

    Getting unexpected error code 0/null/100

    Hi, Thanks for this great library.

    We have added some code curl_getinfo($ch, CURLINFO_HTTP_CODE) to get an exact error code from firebase. Sometimes, we are getting some unexpected error code 0 / null / 100.

    Could you please help me to understand the reason behind such an error code?

    Note: As per firebase documentation, it never returns such error code.

    opened by priyabratap 0
  • No logging in firebaseLib

    No logging in firebaseLib

    is it possible to add an logger into the firebaseLib and log the catched exception messages? At the moment, the curl requests in firebaselib are like blackboxes and it's hard to track issues with connection to firebase

    opened by ChristianSchaefer 0
  • Slow query

    Slow query

    Hi all

    i'm using firebase-php to make a query against a firebase db where i stored chat data.

    the structure is a thing like this

    chat
    ----chat_ID
    ------------node_ID
    

    when i search into a chat (with one or many children) with a code like this

    $firebase = new \Firebase\FirebaseLib(DEFAULT_URL, DEFAULT_TOKEN);
    $value = $firebase->get('/chat/'.$chat, array('orderBy' => '"status"', 'equalTo' => '"unread"'));
    

    the query needs almost 700ms to get a result (even if there is only one node)

    I think it's too much... or not?

    opened by harding13 8
Owner
Tamas Kalman
Tamas Kalman
A composer plugin, to install differenty types of composer packages in custom directories outside the default composer default installation path which is in the vendor folder.

composer-custom-directory-installer A composer plugin, to install differenty types of composer packages in custom directories outside the default comp

Mina Nabil Sami 136 Dec 30, 2022
Drupal Composer Scaffold - A flexible Composer project scaffold builder

This project provides a composer plugin for placing scaffold files (like index.php, update.php, …) from the drupal/core project into their desired location inside the web root. Only individual files may be scaffolded with this plugin.

Drupal 44 Sep 22, 2022
A package for adding more type safety to your PHP projects.

Table of Contents Overview Installation Usage Simple Checks Advanced Checks Custom Checks Skipping Checks Testing Security Contribution Credits Change

Ash Allen 14 Aug 31, 2022
Composer plugin that wraps all composer vendor packages inside your own namespace. Intended for WordPress plugins.

Imposter Plugin Composer plugin that wraps all composer vendor packages inside your own namespace. Intended for WordPress plugins. Built with ♥ by Typ

Typist Tech 127 Dec 17, 2022
The Cache component provides an extended PSR-6 implementation for adding cache to your applications.

Symfony PSR-6 implementation for caching The Cache component provides an extended PSR-6 implementation for adding cache to your applications. It is de

Symfony 3.8k Jan 3, 2023
Dependency graph visualization for composer.json (PHP + Composer)

clue/graph-composer Graph visualization for your project's composer.json and its dependencies: Table of contents Usage graph-composer show graph-compo

Christian Lück 797 Jan 5, 2023
An extension for PHPStan for adding analysis for PHP Language Extensions.

PHPStan PHP Language Extensions (currently in BETA) This is an extension for PHPStan for adding analysis for PHP Language Extensions. Language feature

Dave Liddament 9 Nov 30, 2022
Ied plugin composer - Inspired Plugin Composer: Create, publish and edit plugins from within Textpattern CMS.

ied_plugin_composer Create, publish and edit plugins from within Textpattern CMS. Creates a new page under the Extensions tab where you can edit and e

Stef Dawson 8 Oct 3, 2020
Magento-composer-installer - Composer installer for Magento modules

!!! support the maintainer of this project via Patreon: https://www.patreon.com/Flyingmana Magento Composer Installer The purpose of this project is t

null 213 Sep 24, 2022
Composer Repository Manager for selling Magento 2 extension and offering composer installation for ordered packages.

Magento 2 Composer Repository Credits We got inspired by https://github.com/Genmato. Composer Repository for Magento 2 This extension works as a Magen

EAdesign 18 Dec 16, 2021
Composer registry manager that help to easily switch to the composer repository you want

CRM - Composer Registry Manager Composer Registry Manager can help you easily and quickly switch between different composer repositories. 简体中文 Install

Tao 500 Dec 29, 2022
Composer Registrar Composer Plugin for Magento 2

This module add a global registration.php that replace the default glob search performed for each request to discover the components not installed from composer.

OpenGento 3 Mar 22, 2022
Victor The Cleaner for Composer - This tool removes unnecessary files and directories from Composer vendor directory.

Victor The Cleaner for Composer This tool removes unnecessary files and directories from Composer vendor directory. The Cleaner leaves only directorie

David Grudl 133 Oct 26, 2022
Opinionated version of Wikimedia composer-merge-plugin to work in pair with Bamarni composer-bin-plugin.

Composer Inheritance Plugin Opinionated version of Wikimedia composer-merge-plugin to work in pair with bamarni/composer-bin-plugin. Usage If you are

Théo FIDRY 25 Dec 2, 2022
Envbar allows you to differentiate between environments by adding a custom colored bar above the top navigation.

Envbar Envbar allows you to differentiate between environments by adding a custom colored bar above the top navigation. This should help backend users

Magenizr 6 Oct 7, 2022
A library for adding economic concepts.

PHP use binary version 8.0.10 use PocketMine-MP version API4-beta11+dev2067 Init use oiran\walletlib\api\WalletLib; use oiran\walletlib\api\WarningLev

null 12 Jan 30, 2022
A library for adding economic concepts.

Summary This plugin adds the concept of money to the server. Wallet data held by the player is stored in .json format and I/O asynchronously. As for t

null 12 Jan 30, 2022
Adds support for quickly adding a "snow day" banner at the top of a website.

❄️ Snow Day Plugin ?? Requires OctoberCMS 2.0 ✨ What does this plugin do? Provides the ability to quickly add a cross-site banner using a component. ❓

Albright Labs 4 Nov 7, 2022
This AddOn allows you to search for module names when adding a block

Modulsuche und Modulvorschau für REDAXO 5 Dieses AddOn ermöglicht die Suche nach Modulnamen, wenn man einen Block hinzufügt. Dies kann sehr hilfreich

Friends Of REDAXO 15 Nov 30, 2022