rdlowrey / auryn

IoC Dependency Injector
MIT License
723 stars 65 forks source link

Resolve interfaces and abstracts to shared instances #145

Closed Furgas closed 1 year ago

Furgas commented 8 years ago

Code in question:

interface A { }
class B implements A { }
class C {
    function __construct(A $a) { }
}

$b = new B();
$injector->share($b);

$injector->make(C::class);

Currently this code will fail with exception: Auryn\InjectionException: Injection definition required for interface A

You must explicitly call following to get it working:

$injector->alias(A::class, get_class($b));

or

$injector->alias(A::class, B::class);

What do you think about adding automatic "last resort" resolving of interfaces and abstracts to shared instances? The simplest addition would be at instantiateWithoutCtorParams method:

...
        if (!$reflClass->isInstantiable()) {
            foreach ($this->shares as $sharedObject) {
                if ($sharedObject instanceof $className) {
                    return $sharedObject;
                }
            }
...

Probably it should throw exception when multiple shared objects can be used.

kelunik commented 8 years ago

What if you have two shared objects implementing that interface?

Furgas commented 8 years ago

@kelunik Look at the end of the post:)

Danack commented 8 years ago

What do you think about adding automatic "last resort" resolving of interfaces and abstracts to shared instances?

Honestly, it makes me very sad.

Boostrapping applications shouldn't be magic. Having classes be resolved implicitly just to skip defining the alias function adds a significant amount of implicit behaviour for the small benefit of having to write a line of config.

J7mbo commented 8 years ago

I'm on both sides. I'd love it as an option and there's plenty of 'magic' here anyway.

I can see how being explicit with your aliases is better, like @Danack says. Would this add overhead?

kelunik commented 7 years ago

This relates to #133.

Danack commented 1 year ago

I added some words in 6c06f163800693b712ae9c9bdd601d1c912356eb to explain why it was excluded.

maybe direct link.