使用Laravel的Eloquent ORM调用Slim中的null错误的成员函数connection()

Ken*_*aze 1 orm slim laravel eloquent

我试图在Slim微框架上使用Laravel的Eloquent ORM,但我一直在看错:在null上调用成员函数connection()

这是代码:

dependency.php

$container['db'] = function($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container->get('settings')['database']);

    $capsule->setAsGlobal();
    $capsule->bootEloquent();

    return $capsule;
};
Run Code Online (Sandbox Code Playgroud)

User.php(模型类)

use Illuminate\Database\Eloquent\Model as Model;

class User extends Model {

    protected $table = "users";

    protected $fillable = ['name', 'email', 'password'];
}
Run Code Online (Sandbox Code Playgroud)

HomeController.php(控制器类)

class Home extends Controller {

public function index($request, $response, $args) {
        $user = User::find(1);
        var_dump($user);
        die();
        $title = "Slim Auth";
        $response = $this->view->render($response, 'home.php', ["title" => $title]);
        return $response;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的bootstrap.php文件中需要dependency.php,其中实例化了Slim类:

$config = [
    'settings' => [
        'displayErrorDetails' => true,

        'view' => [
            'view_path' => APP_PATH . 'views/'
        ],

        'database' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'tutorial_slim_auth',
            'username'  => 'root',
            'password'  => 'passw0rd',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ],
    ]
];

$app = new Slim\App($config);
Run Code Online (Sandbox Code Playgroud)

HomeController.php和User.php通过composer json文件自动加载.运行index.php(其中还包括我的bootstrap.php)文件后,包含:

$app->run();
Run Code Online (Sandbox Code Playgroud)

这给了我一个致命的错误:在null上调用成员函数connection().但这样做:

echo '<pre>';
print_r($container['db']);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

在我的bootstrap文件中产生了预期的结果以及HomeController.php文件中调用的var_dump函数的结果.我该怎么办?或者有什么我做得不对劲?

小智 13

您的全局$ capsule封装在这里:

$container['db'] = function($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container->get('settings')['database']);

    $capsule->setAsGlobal();
    $capsule->bootEloquent();

    return $capsule;
};
Run Code Online (Sandbox Code Playgroud)

试试这个:

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();

$container['db'] = function ($container) use ($capsule) {
    return $capsule;
};
Run Code Online (Sandbox Code Playgroud)

第一个版本不起作用的原因是该函数仅在您实际使用胶囊时被调用,即$this->db.如果您只使用Eloquent模型类,则不会进行调用.