Im having trouble understanding how dependency injection actually works, or how to properly use it

Hi!

So I have been trying to build myself an boilerplate with Slim3. And actually, I’m pretty surprised that it is going so smooth, until now.

I want too adapt the MVC design pattern, but due to that I’m having trouble to inject the models into the app. (I think)

So far I can do everything in the controller, that is injected like this, but when trying to use for example $this->pdo from a model, I’m receiving Notice: Undefined property.

When using Eloquent, this is works fine. No need for extra “injection”.

So how to I use a MVC design pattern with slim?

my slim repo

Unless I’m misunderstanding something here, there is no need to get $pdo when using eloquent. You can just do the following

class Users extends Model
{
    ...
}

and then use eloquent in your model code without every having to worry about using PDO. This is all abstracted away in Eloquent.

Hope this helps.

Thanks for your reply! But I’m not using Eloquent.

Its a PDO (FluentPDO) instance I’m trying to use.

You need to define pdo in the container like so…

$container = $app->getContainer();
$container['pdo'] = function ($c) {
    return new \PDO(....);
};

$app->get('/test', function ($req, $res, $args) {
    $this->pdo //do something with pdo
    return $res->write("woo hoo");
});