如何在所需的PHP文件中使用Illuminate数据库实例


How to use Illuminate database instance throughout required PHP files

我正在尝试使用Slim PHP设置一个restful API。这是我第一次使用微框架,我正试图用它构建一个应用程序,使其保持可维护性。

我正在尝试这样构建我的应用程序:

root
- index.php
- composer.json
- app
- - routes
- - - session.php
- - lib
- - - functions.php
- - vendor
- - - Composer Vendor dirs and files

我正在使用Illumination访问我的MySQL数据库,虽然我的所有代码都在index.php文件中,但一切都正常。当我试图将身份验证函数拆分到session.php中时,我再也无法访问照明实例。我遵循了github页面的标准设置

use 'Slim'Slim;
use Illuminate'Database'Capsule'Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver'    => 'mysql',
'host'      => 'localhost',
'database'  => 'database',
'username'  => 'root',
'password'  => 'password',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate'Events'Dispatcher;
use Illuminate'Container'Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$app = new Slim();
//get login routes
require 'app/routes/session.php';
$app->get("/", function() use ($app){
$app->render(200,array(
        'msg' => 'welcome',
    ));
});

这是我的会话php:

$app->post("/login", function() use ($app){
    $postVarsAll = $app->request->post();
    if( isset($postVarsAll['password']) && isset($postVarsAll['username']))
    {
        //Get associated user
        $app->render(200,array(
            'msg' => print_r(Capsule,true)
        ));
        $user = Capsule::table('user')->where('username','=',$postVarsAll['username'])-  >first();
    }else{
    $app->render(200, array(
        "msg" => "no params",
        "params" => $postVarsAll
    ));
    }
});

这抛出了一个500错误,告诉我:

"msg": "NOTICE: Use of undefined constant Capsule - assumed 'Capsule'",

我只想在session.php中使用Capsule实例。有人知道怎么做吗?

如果我拿出胶囊呼叫的路线工作。

谢谢你的帮助!

编辑

$app->post("/login", function() use ($app,$capsule){
    $postVarsAll = $app->request->post();
    if( isset($postVarsAll['password']) && isset($postVarsAll['username']))
    {
        //Get associated user
        $app->render(200,array(
            'msg' => print_r($capsule,true)
        ));
     return;
     ...

用这个我得到了完整的胶囊物体。

编辑2

感谢volkinc找到答案。我可以使用$capsule->table("user")->...来满足我的查询需求。

'msg' => print_r(Capsule,true)

尝试

'msg' => print_r($capsule,true)