I need help with connecting my firebase database with slim framework. I tried using kreait library for firebase, it works only with default php. I need to use slim routes to access my database. Any help is appreciated. Thank you
Hi @ldp.edo98
I tried using kreait library for firebase, it works only with default php.
There is no built-in database or firebase support in Slim. But it should work if you install the kreait/firebase-php
component, configure the firebase credentials (json) and then add a container definition for \Kreait\Firebase\Factory::class
. As soon as you have the Factory instance, you can authenticate your requests to Firebase with a Service Account.
Can you give me an example of the code? I donât understand. Configure firebase credentials where to be specific? Container definition for kreait factory class. I already installed kreait library, it works fine when i run it directly from another file of php, but i canât run it when i call it from routes.
but i canât run it when i call it from routes.
You should give more details like a code snippet, an error messages or something like this.
this is my routes.php
<?php
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use OurOwnNameSpace\testClass as test;
return function (App $app) {
$container = $app->getContainer();
$app->get("/edo", function (Request $request, Response $response){
return test::get(1);
});
};
this is my working outside class, this class works when i call it directly from localhost using var_dump
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
require __DIR__ . '/../vendor/autoload.php';
class Users {
protected $database;
protected $dbname='users';
public function __construct(){
$acc=ServiceAccount::fromJsonFile(__DIR__. '\secret\tugasakhir-273202-6ee1f9786c82.json');
$firebase=(new Factory)->withServiceAccount($acc)->create();
$this->database=$firebase->getDatabase();
}
public function get(int $userID = NULL){
if (empty($userID) || !isset($userID)) { return false; }
if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){
return $this->database->getReference($this->dbname)->getChild($userID)->getValue();
} else {
return false;
}
}
public function insert(array $data){
if (empty($data) || !isset($data)) { return false; }
foreach ($data as $key => $value){
$this->database->getReference()->getChild($this->dbname)->getChild($key)->set($value);
}
return true;
}
public function delete(int $userID){
if (empty($userID) || !isset($userID)) { return false; }
if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){
$this->database->getReference($this->dbname)->getChild($userID)->remove();
return true;
} else {
return false;
}
}
}
//$users=new Users();
// var_dump($users->insert([
// '1'=>"John",
// '2'=>"Leo"
// ]));
//var_dump($users->get(2));
this is my testClass which i want to call from routes.php, i try to use function get but it shows error
<?php
namespace OurOwnNameSpace;
class testClass {
protected $database;
protected $dbname='users';
public function __construct() {
$acc=ServiceAccount::fromJsonFile(__DIR__. '\secret\tugasakhir-273202-6ee1f9786c82.json');
$firebase=(new Factory)->withServiceAccount($acc)->create();
$this->database=$firebase->getDatabase();
}
public function get(int $userID = NULL){
if (empty($userID) || !isset($userID)) { return false; }
if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){
return $database->getReference($this->dbname)->getChild($userID)->getValue();
} else {
return false;
}
}
public function testing() {
return 'Happy Test';
}
}
this is the error that shows when i run my slim app
Slim Application Error
The application could not run because of the following error:
Details
Type: Error
Message: Using $this when not in object context
File: C:\xampp\htdocs\Service_TA\src\class\testClass.php
Line: 18
Trace
#0 C:\xampp\htdocs\Service_TA\src\routes.php(14): OurOwnNameSpace\testClass::get(1)
#1 [internal function]: Closure->{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#2 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Handlers\Strategies\RequestResponse.php(40): call_user_func(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#3 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(281): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#4 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#5 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(268): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#6 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(503): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#7 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#8 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(392): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(297): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 C:\xampp\htdocs\Service_TA\public\index.php(46): Slim\App->run()
#11 {main}
thank you very much for helping me
Sorry, itâs not readable
You can format source code in this tags:
```php
// source code goes here
```
(Iâve applied the formatting to that post.)
Message: Using $this when not in object context
Thatâs a PHP specific issue.
Here you invoke a non static method like a static method: return test::get(1);
But in your testClass
the method get($id)
is not static.
Instead you should create an instance of âtestClassâ first, e.g.
$app->get("/edo", function (Request $request, Response $response) {
$test = new \OurOwnNameSpace\testClass();
$result = $test->get(1);
$response = $response->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string)json_encode($result));
return $response;
}
i did what you told me to do. i copied your code to my routes.php. it shows this error. is it error within the library? i think it shouldnât be OurOwnNameSpace\ServiceAccount. but i donât know where the problem is
Slim Application Error
The application could not run because of the following error:
Details
Type: Error
Message: Class âOurOwnNameSpace\ServiceAccountâ not found
File: C:\xampp\htdocs\Service_TA\src\class\testClass.php
Line: 16
Trace
#0 C:\xampp\htdocs\Service_TA\src\routes.php(15): OurOwnNameSpace\testClass->__construct()
#1 [internal function]: Closure->{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#2 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Handlers\Strategies\RequestResponse.php(40): call_user_func(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#3 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(281): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#4 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#5 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(268): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#6 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(503): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#7 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#8 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(392): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(297): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 C:\xampp\htdocs\Service_TA\public\index.php(46): Slim\App->run()
#11 {main}
. is it error within the library?
No, Slim works. Your composer autoloader is just not configured properly. You should fix that first. Read about composer and PSR-4. You can also find some explanations for Slim 4 here.
i already dump my autoload.
this is my composer.json
i canât use " ``` " tag for inserting code
so i just upload my screenshot. i donât think
i donât understand at all
The âautoloadâ section is missing in your composer.json file. Separate the default namespaces from the dev namespaces. Add an application specific namespace e.g. App
that points to /src
. The src/ path is for all your PHP classes and sub-namespaces under \App\*
.
Here is an example:
"autoload": {
"psr-4": {
"App\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"App\\Test\\": "tests"
}
}
Move the file testClass.php
to src/
.
Rename the file testClass.php
to TestClass.php
Rename the class testClass
to TestClass
Change the namespace OurOwnNameSpace
to App
.
Update all references to the new TestClass (e.g. in your routes)
Run composer update.
Try it again.
Read more about it: https://odan.github.io/2019/11/05/slim4-tutorial.html#psr-4-autoloading
i followed your tutorial at that link. still shows error. first i followed your email, it shows the same error with before. Then i try to follow at your link, it shows another error but i think itâs quite the same.
Slim Application Error
The application could not run because of the following error:
Details
Type: RuntimeException
Message: Callable App\Src\TestClass does not exist
File: C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\CallableResolver.php
Line: 99
Trace
#0 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\CallableResolver.php(58): Slim\CallableResolver->resolveCallable('App\\Src\\TestCla...', '__invoke')
#1 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\CallableResolverAwareTrait.php(41): Slim\CallableResolver->resolve('App\\Src\\TestCla...')
#2 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(276): Slim\Routable->resolveCallable('App\\Src\\TestCla...')
#3 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#4 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\Route.php(268): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#5 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(503): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#6 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#7 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(392): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#8 C:\xampp\htdocs\Service_TA\vendor\slim\slim\Slim\App.php(297): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 C:\xampp\htdocs\Service_TA\public\index.php(46): Slim\App->run()
#10 {main}
The src/ directory is the root directory for the App namespace. âSrcâ must not be part of a namespace. In your case it should be App\TestClass
(not App\Src\TestClass
). Please note that itâs just an example.
App\TestClass doesnât exist
i tried composer update, composer dump-autoload
Then better check out a Slim-skeleton project with a working autoloader:
i downloaded a working slim autoload in github, they use slim skeleton or something. i tried modifying it a little bit like this.
i created a class in file src named Coba.php
created a simple function
public function print() { return "Printing" }
then at the routes i tried to call it like this
$app->get('/', function (Request $request, Response $response) {
$iniclass=new App\Coba();
$result = $iniclass->print();
$response = $response->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string)json_encode($result));
return $response;
});
it shows this error
{
"statusCode": 500,
"error": {
"type": "SERVER_ERROR",
"description": "Class 'Slim\\App\\Coba' not found"
}
}
here is my directory
is there anything i did wrong?
i tried inserting $result with pure string and it works fine, something like âblablablaâ
Try: $iniclass = new \App\Coba();
PS:
- The code is not readable:
- You really should learn the basics of PHP classes, namespaces, use statements, PSR-4 autoloader first.
(Iâve tried to cleanup the initial post as best I could.)