auryn icon indicating copy to clipboard operation
auryn copied to clipboard

Resolve interfaces and abstracts to shared instances

Open Furgas opened this issue 9 years ago • 5 comments
trafficstars

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.

Furgas avatar May 20 '16 09:05 Furgas

What if you have two shared objects implementing that interface?

kelunik avatar May 20 '16 09:05 kelunik

@kelunik Look at the end of the post:)

Furgas avatar May 20 '16 09:05 Furgas

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.

Danack avatar Jul 31 '16 13:07 Danack

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?

J7mbo avatar Jul 31 '16 14:07 J7mbo

This relates to #133.

kelunik avatar Jan 09 '17 12:01 kelunik

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

maybe direct link.

Danack avatar Jan 11 '23 15:01 Danack