简体   繁体   中英

PHP Slim framework database class not working

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();

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

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";
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM