Reputation: 4496
I've been banging my head against this for hours yet I can't seem to figure out the issue, essentially I have a library file that gets called in all over the place and works everywhere fine except where i'm calling it in here.
I can get slim to work fine until I try access the db object and query anything? Im probably being dim but this is more or less exactly how it says to do it in the slim docs with a couple of extra lines thrown in so it doesn't make sense that it stops working.
require_once "libary.php";
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/login/:username/:password', function ($username, $password) {
//check the login details against the db...
echo "I SEE THIS";
$query = "select * from sometable";
$db->query($query);
echo "I DONT SEE THIS";
});
$app->run();
Upvotes: 0
Views: 2440
Reputation: 61
You can also inject your database into the app as singleton thus:
$app->container->singleton('db', function () use ($dbcfg){
return new \myDatabaseClass($dbcfg);
});
and then it will always be available to you here:
$app->db->query();
See this for more details: http://docs.slimframework.com/#DI-Overview
Upvotes: 1
Reputation: 61
You can avoid the using GLOBAL with the use keyword (PHP >= 5.3.0):
$app->get('/login/:username/:password', function ($userstrong textname, $password) use ($db) {
//check the login details against the db...
echo "I SEE THIS";
$query = "select * from sometable";
$db->query($query);
echo "I DONT SEE THIS";
});
Upvotes: 1
Reputation: 4496
Sorry for the slow response, rather embarrassing but all that was needed was to insert one line of code into that inline function:
GLOBAL $db
I had assumed(incorrectly) that variable would be visible from within the function since it was defined in our library.
Thanks
Marc
Upvotes: 1