brslv brslv - 3 months ago 15
PHP Question

Injecting objects, which extends from a parent class in Slim

I'm playing around with Slim PHP framework and stumbled upon a situation I cannot work out.

First, I'll explain the basic setup:

Using slim-skeleton, I have a dependencies.php file, where the DIC is set up. It's the default slim-skeleton's setup with two more things:

$container['db'] = function ($c) {
return new PDO('mysql:host=localhost;dbname=****', '********', '********');
};

$container['model.user'] = function ($c) {
$db = $c['db'];
return new Dash\Models\User($db);
};


So, as you can see, I have two new things registered in the DIC - A PDO object and a User object.

But passing a database object for each and every other model is a bit of a pain... I would like to be able to inject the PDO object to a parent class, called Model.

So the Model should look like this:

class Model
{
protected $db;

public function __construct($db)
{
$this->db = $db;
}
}


And the User model:

class User extends Model
{
public function getById($id)
{
$this->db->... // I have access to the database object (PDO) from the parent class.
}
}


The thing is that I cannot have a parent object, because the slim's container returns a new instance of User and does not instantiate the parent Model class.

Any ideas on how to achieve inheritance, using Slim's container in a clean and usable way?

Thanks in advance.

Answer

That's not how inheritance works. User is an instance of Model. So when you do new User($c['db']), it'll work fine.

Comments