2

So we've got a container, service providers and, with inversion of control, we can do fancy stuff like:

public function __construct(CarServiceInterface $carService)
{
}

And things get resolved nicely because somewhere else...

$container->bind(CarServiceInterface::class, function ()
{
    return new CarService();
});

Let's say car service depends on human service. Then...

    $container->bind(CarServiceInterface::class, function (Container $container)
    {
        return new CarService($container->make(HumanServiceInterface::class);
    });

Hey, that works. Cool.

But then suddenly humans NEED cars, and the human service is built like this:

$container->bind(HumanServiceInterface::class, function (Container $container)
{
   return new HumanService($container->make(CarServiceInterface::class);
});

Voila, cross dependency.

How to solve this?

Is this consequence of a flaw in the design?

Thanks!

Hector Ordonez
  • 1,044
  • 1
  • 12
  • 20

1 Answers1

2

I think this would be called 'Circular dependencies' (see here for more about this).

The answer says that there's no way to do this, and that the only way to use a circular dependency is to use setter injection, instead of the usual constructor injection.

Community
  • 1
  • 1
jeroenvisser101
  • 856
  • 10
  • 23