Mushr00m's avatar

Dependency Injection and inheritance

Hi all,

I have an Abstract repository where I want to set some parameters for all my Repos. Like for example the number of item for the pagination. So I was thinking of doing :

abstract class AbstractRepository
{
 protected $model;
 protected $config;

public function __construct(Model $model, Config $config)
{
    $this->model = $model;
    $this->config = $config;
}
...

But then when in my UserRepo class that Extends this AbstractRepo I do :

public function __construct(User $user)
{
    parent::__construct($user);
}

It give me an error about the fact that the second parameter is none. So when using DI we "can't" use inheritance to let the IOC do the work ?

Also a more PHP global question. On the same inheritance example, with namespace, if I declare "use Config;" in my abstract class I still have to redeclare it in the classes that extends the abstract class ? There is no cascading here ?

Thanks !

0 likes
1 reply
JohnRivs's avatar

The IoC is not a magician, it doesn't know about your class. Somewhere (probably a Service Provider) you gotta tell Laravel about your (abstract) class, and how to build it everytime you want it resolved.

If you declare 'use Config;' on AbstractRepository.php, you'll have to declare it on UserRepo.php, whether UserRepo extends AbstractRepository or not.

Please or to participate in this conversation.