2
votes

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 = "[email protected]";
    $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

1 Answers

2
votes

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.