Skip to content

Instantly share code, notes, and snippets.

@warlord0
Created September 30, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warlord0/977c8ec955ad4b0c23739a23703a7372 to your computer and use it in GitHub Desktop.
Save warlord0/977c8ec955ad4b0c23739a23703a7372 to your computer and use it in GitHub Desktop.
FireSyncObserver - Synchronise a Laravel Model with Firebase
<?php
/**
* FireSync Observer
*
* Watch for changes and replicate them to the Firebase database
*
* PHP Version 7.1
*
* @category Observer
* @package Firebase
* @license GPLv3.0 GNU Public License v3.0
*/
namespace App\Observers;
use App\FireSync;
use Kreait\Firebase\Factory;
use Illuminate\Support\Facades\Log;
/**
* FireSync Observer
*
* Watch for changes and replicate them to the Firebase database
*
* @category Observer
* @package Firebase
* @license GPLv3.0 GNU Public License v3.0
*/
class FireSyncObserver
{
private $_database;
private $_baseReference = 'recordset/records';
private $_reference;
/**
* Constructor
*/
public function __construct()
{
$this->_database = (new Factory)->createDatabase();
$this->_reference = $this->_database->getReference($this->_baseReference);
}
/**
* Created event
*
* Takes the newly created row and adds it to the firebase record set
*
* @param FireSync $fireSync The Database model
*
* @return void
*/
public function created(FireSync $fireSync)
{
$row = $fireSync->toArray();
$pushKey = $this->_database->getReference(
$this->_baseReference
)
->push($row)->getKey();
Log::debug('Create called for ' . $pushKey);
$fireSync['push_key'] = $pushKey;
// Call an update of the local table to add the push_key without
// triggering any updated event.
FireSync::withoutEvents(
function () use ($fireSync) {
$fireSync->save();
}
);
}
/**
* Updated Event
*
* When a row is updated update the firebase record set to match.
* Fairly lazy as it updates ALL columns, not just those that have changed.
*
* @param FireSync $fireSync Database model
*
* @return void
*/
public function updated(FireSync $fireSync)
{
if ($fireSync['push_key'] !== null) {
Log::debug('Update called for ' . $fireSync['push_key']);
// Grab all the columns except push_key
$row = $fireSync->makeHidden('push_key')->toArray();
$this->_database->getReference(
$this->_baseReference . '/' . $fireSync['push_key']
)
->set(
$row
);
}
}
/**
* Deleted Event
*
* When a row is deleted remote the matching model from firebase.
*
* @param FireSync $fireSync Database model
*
* @return void
*/
public function deleted(FireSync $fireSync)
{
if ($fireSync['push_key'] !== null) {
Log::debug('Delete called for ' . $fireSync['push_key']);
$this->_database->getReference(
$this->_baseReference . '/' . $fireSync['push_key']
)
->remove();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment