简体   繁体   English

PHP Slim框架数据库类不起作用

[英]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? 在尝试访问db对象并查询任何内容之前,我可以变得苗条,可以正常工作。 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 全局$ 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): 您可以避免通过use关键字(PHP> = 5.3.0)使用GLOBAL:

$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 请参阅此以获取更多详细信息: http : //docs.slimframework.com/#DI-Overview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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