How to trigger Eloquent Manager in Slim 3.1 Dependency Injection

我的梦境 提交于 2019-12-22 14:54:08

问题


I have write my code to instantiate Eloquent Capsule/Manager using slim DI like this

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

And I have my route like this

$app->get('/adduser', function() {
    $user = new Users;
    $user->name = "Users 1";
    $user->email = "user1@test.com";
    $user->password = "My Passwd";
    $user->save();
    echo "Hello, $user->name !";
});

When I run the route in browser it will produce error in web server error log

PHP Fatal error: Call to a member function connection() on a non-object in /home/***/vendor/illuminate/database/Eloquent/Model.php on line 3335

In my opinion this is happened because the Eloquent Capsule/Manager is not triggered to be instantiate by DI.

I found a solution to solve this by declare the Model with custom constructor like this

use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Capsule\Manager as Capsule;

class Users extends Eloquent {
    protected $table = 'users';
    protected $hidden = array('password');

    public function __construct(Capsule $capsule, array $attributes = array())
    {
        parent::__construct($attributes);
    }
}

But I don't think this is a clean solutions, because I have to rewrite all my Models using custom constructor.

I need help to find solutions for my problem. I try to use code below:

$app->get('/adduser', function() use ($some_variable) {
   // create user script
});

but so far I don't know how to trigger $container['db'] using this method. I really appreciate a help here.


回答1:


It's probably not a good idea to inject your capsule manager into each model.. As you say yourself, that's going to be a pain to manage. Have you tried this code outside of the closure? ie. in the bootstrap part of your app..

 $db = new \Illuminate\Database\Capsule\Manager;
 $db->addConnection($settings);
 $db->setAsGlobal();
 $db->bootEloquent();

The setAsGlobal function makes the Capsule Manager instance static, so the models can access it globally. Just to note, convention is to name your model classes in singular form. ie. User rather than Users.



来源:https://stackoverflow.com/questions/35411954/how-to-trigger-eloquent-manager-in-slim-3-1-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!