我正在尝试使用Slim PHP设置一个restful API。这是我第一次使用微框架,我正在尝试用它构建一个应用程序,以便它可以保持可维护状态。
我正在尝试构建我的应用程序:
root
- index.php
- composer.json
- app
- - routes
- - - session.php
- - lib
- - - functions.php
- - vendor
- - - Composer Vendor dirs and files
我正在使用illuminate访问我的MySQL数据库,而我在index.php文件中的所有代码都工作正常。当我试图将我的身份验证功能分解到session.php时,我无法再访问illuminate实例。我按照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',
));
});
这是我的session.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实例。有谁知道怎么做?
如果我取出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;
...
用这个我得到完整的胶囊对象。
感谢volkinc寻找答案。
我可以使用$capsule->table("user")->...
来满足我的查询需求。
答案 0 :(得分:2)
'msg' => print_r(Capsule,true)
尝试
'msg' => print_r($capsule,true)