0

I am trying to do dependency injection.

But when i call my BananaService i get error:

TypeError: Argument 1 passed to BananaService::\__construct() must be an instance of BananaFactory, instance of BananaModelFactory given.

which sounds quite logical, but it seemed to me that it should just return a BananaModelFactory class when it sees an BananaFactoryInterface, and not an error.

I have this BananaService:

class BananaService
{
    public function __construct(BananaFactory $factory) {
        $this->factory = $factory;
    }
}

My BananaFactoryInterface:

interface BananaFactory
{
    public function make(array $attributes = []): BananaEntity;
}

And BananaModelFactory:


class BananaModelFactory
{
    public function make(): BananaEntity
    {
        return new Banana($attributes);
    }
}

I also added the following code to the AppServiceProvider:

public function register()
{
    $this->app->bind(BananaFactory::class, BananaModelFactory::class);
}

1 Answer 1

1

I forgot to do an implementation in my BananaModelFactory.

class BananaModelFactory implements BananaFactory {} instead of class BananaModelFactory {}.

I also found an excellent github gist in which it is written in detail about binding interfaces to implementation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.